数据请求我们可以使用axios来做数据拦截,但是具体请求时还是需要用uni-app提供的uni.request()API,例如:
// request.js
import axios from 'axios'
import qs from 'qs'
// 创建axios实例
const service = axios.create();
const baseUrl = ''; // 此处填写接口相对URL,用于拼接在url前面
service.defaults.timeout = 30000;
service.defaults.baseURL = baseUrl;
axios.defaults.adapter = function(config) {
return new Promise((resolve, reject) => {
let data = config.method === 'get' ? config.params : config.data;
uni.request({
url: baseUrl + config.url,
method: config.method || 'get',
header: {
'content-type': 'application/x-www-form-urlencoded'
},
data: data,
success: (res) => {
return resolve(res)
},
fail: (err) => {
return reject(err)
}
})
})
};
// request拦截器
service.interceptors.request.use(
config => {
uni.showLoading({
title: '加载中'
});
if (config.method === 'post') {
config.data = qs.stringify(config.data);
}
return config;
},
error => {
console.log(error)
Promise.reject(error)
}
);
// response 拦截器
service.interceptors.response.use(
response => {
uni.hideLoading();
const res = response.data;
if (res.code === 500) {
uni.showToast({
icon: 'none',
title: res.msg
});
return Promise.reject('error')
} else {
return response.data
}
},
error => {
uni.showToast({
icon: 'none',
title: '未知错误'
});
return Promise.reject(error)
}
)
export default service;
// index.js
import request from './request.js';
// 请求列表
export function getList(data) {
return request({
url: '/list',
params: data
});
}