1、拦截器 request.js
// 根域名
var baseUrl = 'https://xxx.com;
module.exports = (vm) => {
// 初始化请求配置:config 为默认全局配置
uni.$u.http.setConfig((config) => {
config.baseURL = baseUrl; /* 根域名 */
// 配置请求头信息
config.header = {
'content-type': 'application/x-www-form-urlencoded;charset=UTF-8',
// 'content-type': 'application/json',
};
config.method = 'GET'; //支持post、get、put、delete
config.dataType = 'json'; // 设置为json,返回后会对数据进行一次JSON.parse()
config.timeout = 60000;
return config
})
// 请求拦截
uni.$u.http.interceptors.request.use((config) => { // 可使用async await 做异步操作
// 初始化请求拦截器时,会执行此方法,此时data为undefined,赋予默认{}
config.data = config.data || {};
// 设置token
const token = uni.getStorageSync('token') || '';
config.header['token'] = token;
// 设置设备端类型
// config.header['os'] = uni.$u.os() || '';
return config;
}, config => { // 可使用async await 做异步操作
return Promise.reject(config)
})
// 响应拦截
uni.$u.http.interceptors.response.use((response) => {
/* 对响应成功做点什么 可使用async await 做异步操作*/
const res = response.data;
// console.log(res)
// res为服务端返回值,可能有code,result等字段
if (res.code == 0) {
return res;
} else if (res.code == 400) {
uni.$u.toast(res.msg)
return false;
} else if (res.code == 401) {
// 401为token失效
uni.setStorageSync('token', ''); // 缓存token
uni.$u.toast(res.msg)
setTimeout(() => {
vm.$u.route('/pages/login/login')
}, 1500)
return false;
} else if (res.code == 405) {
// 405为token为空
return false;
} else if (res.code == 1) {
uni.$u.toast(res.msg)
return false;
} else {
// 如果需要catch返回,则进行reject
return Promise.reject(res)
}
}, (response) => {
// 对响应错误做点什么 (statusCode !== 200)
return Promise.reject(response)
})
}
2、请求示例
// get请求
uni.$u.http.get('/api/xxx', {
params: {}
}).then(res => {
console.log("==get请求结果==");
console.log(res);
}).catch(err => {
console.log(err);
})
// post请求
uni.$u.http.post('/api/xxx', {
}).then(res => {
console.log("==post请求结果==");
console.log(res);
}).catch(err => {
console.log(err);
})
// 临时调整post请求头格式
uni.$u.http.post('/api/xx', {
id: '',
}, {
header: {
'content-type': 'application/json',
}
}).then(res => {
console.log("==自定义表单结果==");
console.log(res);
}).catch(err => {
console.log(err);
})
// upload上传请求
uni.$u.http.upload('/api/plus.Upload/imgUpload', {
filePath: filePath,
name: 'file',
formData: {},
}).then(res => {
console.log("==upload上传请求结果==");
console.log(res);
}).catch(err => {
console.log(err);
})