问题原因
uni-app
拦截了所有非uni.request
发送的请求
解决方案
上文说到uni-app
拦截了所有非uni.request
发送的请求,所以下面需要将axios
转发使用uni.request
发送网络请求,步骤如下
- 在
Axios
,AxiosRequestConfig
配置类中有一个adapter
的配置属性,他的作用就是让用户何以自定义请求策略,AxiosRequestConfig
属性如下:
export interface AxiosRequestConfig<D = any> {
...
timeout?: Milliseconds;
timeoutErrorMessage?: string;
withCredentials?: boolean;
adapter?: AxiosAdapterConfig | AxiosAdapterConfig[];
auth?: AxiosBasicCredentials;
responseType?: ResponseType;
responseEncoding?: responseEncoding | string;
...
}
上文可以看到存在一个adapter
的属性,接下来,开始配置它,代码附上
import axios from "axios";
import type { AxiosResponse } from 'axios'
const _axios = axios.create({
timeout: 60000
});
_axios.interceptors.request.use((config) => {
config.url = config.baseURL + config.url;
return config;
})
_axios.interceptors.response.use((response) => {
return {
data: response.data,
status: response.statusCode,
message: response.statusText
}
})
_axios.defaults.adapter = (config) => {
return new Promise<AxiosResponse<string | AnyObject | ArrayBuffer>>((resolve, reject) => {
//这里使用uni-app的请求方法发送请求
uni.request({
method: (config.method || 'GET').toUpperCase(),
url: config.url,
header: config.headers,
data: config.data || config.params,
dataType: config.responseType,
responseType: config.responseType,
sslVerify: config.withCredentials,
success: (res) => {
resolve({
data: res.data.data || null,
status: res.statusCode,
statusText: res.data.message || "",
headers: res.header,
config: config
})
},
fail: (error) => {
reject(error)
}
})
})
}
export function useApi() {
return _axios;
}