uniapp+axios请求的封装
因在用vue3.0时会导致无法引有buildFullPath和settle两个库。所简单处理这两个方法
// utils/request.ts文件代码如下
javascript
/***
uniapp+axios请求的封装
**/
import axios from 'axios'
import $config from "@/config/config"
import {getToken,removeToken} from "@/utils/auth"
// create an axios instance
//创建axios实例
const service = axios.create({
baseURL: process.env.NODE_ENV === 'development' ? $config.baseUrl.dev : $config.baseUrl.pro,
withCredentials: true, // send cookies when cross-domain requests
timeout: $config.timeout,// request timeout
headers:{
'Content-Type':'application/json;charset=utf-8'
}
})
//响应请求
service.interceptors.request.use(
config => {
if (config.headers.auth) { // 判断请求是否需要认证
if(getToken()) config.headers['Authorization'] ='Authorization '+getToken();
}
return config
},
error => {
return Promise.reject(error)
}
)
//响应拦截器
service.interceptors.response.use(({config,data}) => {
console.log(data)
if (data.code === 'A0230') { // token过期
if(getToken()){
uni.showToast({
icon:"loading",
title: '会话已过期,重新获取',
success() {
removeToken() //删除Token
console.log('失败处理')
}
})
}
}
},error => {
const {code,msg} = error.response.data
if (code === 'A0230') { // token过期
if(getToken()){
uni.showToast({
icon:"loading",
title: '会话已过期,重新获取',
success() {
removeToken() //删除Token
console.log('失败处理')
}
})
}
} else {
uni.showToast({
title: msg,
icon: 'none'
});
return Promise.reject(new Error(msg || 'Errors'))
}
}
)
//自己定义个适配器,用来适配uniapp的语法
service.defaults.adapter = function(config) {
return new Promise((resolve, reject) => {
//if(typeof config.data==="string") data=JSON.parse(config.data) //TODO GET会变成string
uni.request({
method: config.method.toUpperCase(),
url: combineURLs(buildFullPath(config.baseURL,config.url), config.params, config.paramsSerializer),
header: {...config.headers},
data:config.data,
complete:(response)=>{
response = {
data: response.data,
status: response.statusCode,
errMsg: response.errMsg,
header: response.header,
config: config.data
};
settle(resolve, reject, response);
}
})
})
}
function buildFullPath(baseURL, requestedURL) {
console.log(buildURL(requestedURL));
if (baseURL && !buildURL(requestedURL)) {
return combineURLs(baseURL, requestedURL);
}
return requestedURL;
}
function buildURL(url) {
// A URL is considered absolute if it begins with "<scheme>://" or "//" (protocol-relative URL).
// RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed
// by any combination of letters, digits, plus, period, or hyphen.
return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(url);
}
function combineURLs(baseURL, relativeURL) {
return relativeURL
? baseURL.replace(/\/+$/, '') + '/' + relativeURL.replace(/^\/+/, '')
: baseURL;
}
function settle(resolve, reject, response) {
let validateStatus = response.config.validateStatus;
if (!response.status || !validateStatus || validateStatus(response.status)) {
resolve(response);
} else {
reject(createError(
'Request failed with status code ' + response.status,
response.config,
null,
response.request,
response
));
}
};
export default service
使用封装的例子
//aip/auth.ts
javascript
/**
* 用户
**/
import request from '@/utils/request'
/**
* 反馈信息
* @param {*} type
* @param {*} contact_mobile
* @param {*} content
* @param {*} images
*/
export function getBanner(data) {
return request({
url:`/index/banner`,
method: 'POST',
data:data,
headers: {
'auth': true// 需要认证,通过
}
})
}