在uniapp项目根目录里面新建一个文件 utils:
![](https://img-blog.csdnimg.cn/46904fadd6bb46759d596a2a73e9d7e9.png)
再新建一个api.js:
//你的请求地址(线上或线下)
const BASE_URL = 'https://www.baidu.com/'
export const http = (options) => {
return new Promise((resolve, reject) => {
uni.request({
url: BASE_URL + options.url,
method: options.method || 'POST',
header: {
'content-type': 'application/x-www-form-urlencoded',
},
data: options.data || {},
success: (res) => {
//报错逻辑
if (res.statusCode !== 200) {
uni.showToast({
icon: 'none',
title: res.data.message
})
} else if (res.statusCode == 400) {
return uni.showToast({
icon: 'none',
title: res.data.message
})
}
resolve(res);
},
fail: (err) => {
uni.showToast({
icon: 'none',
title: '请求失败!'
})
reject(err)
}
})
})
}
在main.js中引入
// 封装的http请求
import {http} from 'utils/api.js'
Vue.prototype.$http = http
接口使用方法:
this.$http({
url: 'api/sss/delelt',
method: 'POST',//不写默认为post
//带参数
data: {
type: 1,
}
}).then(res => {
console.log(res);
})