1、在新建好的uniapp项目中新建一个文件夹common,再建一个request.js文件(有人喜欢叫api.js都可以)
2. 在request.js放入以下代码
let baseUrl = ""
export default {
request(options = {}) {
let types = ""
options["method"] === "POST" && Object.keys(options.header).length !== 0 ? types = options["header"] : types =
"application/json"
let token = uni.getStorageSync("token") || ""
return new Promise((resolve, reject) => {
uni.request({
url: baseUrl + options.url,
data: options.data,
method: options.method,
header: {
'Content-Type': types,
'Accept': 'application/json, text/javascript, */*; q=0.01',
'Authorization': token
},
success: (result) => {
switch (result["statusCode"]) {
case 401:
uni.showModal({
title: "登录提示",
content: "身份已过期,请重新登录后再来操作",
success: (res) => {
if (res.confirm) {
uni.redirectTo({
url: "/subpkgLogin/shortMsgLogin/shortMsgLogin"
})
}
}
})
break;
default:
resolve(result)
break;
}
},
fail: (error) => {
uni.showToast({
title: "数据加载失败,请稍后再试",
duration: 1500,
icon: "error"
})
reject(error)
}
})
})
},
// get 请求体
get(url = "", data = {}, header = {}) {
return this.request({
url,
data,
method: "GET",
header
})
},
// post 请求体
post(url = "", data = {}, header = {}) {
return this.request({
url,
data,
method: "POST",
header
})
},
// delete 请求体
del(url = "", data = {}, header = {}) {
return this.request({
url,
data,
method: "DELETE",
header
})
}
}
3、在main.js中全局挂载
4、在页面中使用
// post 方法
this.$http.post(`url`, {
data参数
}, "header")
.then(res => {
console.log(res)
})
// get 方法
this.$http.get(`url`, {
data参数
}, "header")
.then(res => {
console.log(res)
})
// delete 方法
this.$http.del(`url`, {
data参数
}, "header")
.then(res => {
console.log(res)
})