import '@/common/api/interceptor.js'; // 引入拦截器文件
export default{common:{baseUrl:"http://localhost:3000/api",data:{},header:{"Access-Control-Allow-Origin":"*","Content-Type":"application/json","Content-Type":"application/x-www-form-urlencoded"},method:"GET",dataType:"json"},//封装为选项对象request( options={} ){uni.showLoading({title: '加载中'});options.url = this.common.baseUrl + options.url;options.data = options.data || this.common.data;options.header = options.header || this.common.header;options.method = options.method || this.common.method;options.dataType = options.dataType || this.common.dataType;return new Promise((res,rej)=>{uni.request({...options,success: (result) => {// if(result.statusCode===401) 进行类似过滤器的操作if(result.statusCode != 200){// 使其可以使用catchreturn rej();}setTimeout(function () {uni.hideLoading();}, 1500);let data = result.data;// res里面就是请求体了 可以直接获取自己定义的code 和数据res(data);}})})}
}
这样就把uniapp的回调ajax封装为了resolve,这里还类似封装了axios的拦截器
// utils/interceptors.js// 请求拦截器
uni.addInterceptor('request', {// 在发送请求之前执行invoke(request) {// 在请求发送前可以进行一些操作,例如添加请求头、设置认证信息等request.header = {'Content-Type': 'application/json', // 设置 Content-Type 请求头'Authorization': 'Bearer your-token', // 设置 Authorization 请求头};console.log('------请求拦截器------');return request;},// 请求出错时执行fail(error) {console.error('请求拦截器出错', error);return error;},
});// 响应拦截器
uni.addInterceptor('response', {// 在响应返回之后执行invoke(response) {// 对响应数据进行处理console.log('响应拦截器');response.header={"Access-Control-Allow-Origin":"*"}return response;},// 响应出错时执行fail(error) {console.error('响应拦截器出错', error);return error;},
});