1、创建request全局配置文件
在uniapp官网有这样一段话:
header
默认的请求时header['content-type']
为application/json
- 对于
POST
方法且header['content-type']
为application/json
的数据,会进行 JSON 序列化。- 对于
POST
方法且header['content-type']
为application/x-www-form-urlencoded
的数据,会将数据转换为 query string。在全局配置文件中设置 请求拦截,通过拦截到的 自定义接口传参 判断是否修改header里面的content-type传参形式;
module.exports = (vm) => {
// 初始化请求配置
// 设置跨域问题
// #ifdef H5
// 此为自定义配置参数,具体参数见上方说明
uni.$u.http.setConfig({
baseUrl: 'api',
loadingText: '努力加载中~',
loadingTime: 800,
// ......
});
// #endif
// #ifndef H5
// 此为自定义配置参数,具体参数见上方说明
uni.$u.http.setConfig({
baseUrl: 'http://192.168.xx.xx:xxxxx',
loadingText: '努力加载中~',
loadingTime: 800,
// ......
});
// #endif
// 请求拦截
uni.$u.http.interceptor.request = (config) => {
//通过 CONTENTTYPE 自定义的请求参数来判断的 是requestBody传参还是普通的query传参请求
config.header['Content-Type'] = config.header.CONTENTTYPE || 'application/json'
return config
}, config => { // 可使用async await 做异步操作
return Promise.reject(config)
}
}
在main.js中使用
import App from './App'
App.mpType = 'app'
const app = new Vue({
...App
})
// 引入请求封装,将app参数传递到配置中
require('@/config/request.js')(app)
2、请求得api封装
const http = uni.$u.http
//通过自定义的 CONTENTTYPE 来修改是 query 传参模式
export const httpCustom= (params = {}) => http.post('url', params, {
'CONTENTTYPE': 'application/x-www-form-urlencoded'
})
//这个是是 requestBody 传参模式 不需要传 CONTENTTYPE
export const http= (data) => http.post('url', data)
uniapp官网~网络https://uniapp.dcloud.io/api/request/request.html