uni-app 请求封装成axios
由于原生的uni-app的请求没有拦截守卫, 我用的不爽。 于是自行封装了
请求使用参数 与 uniapp使用一致
https://uniapp.dcloud.io/api/request/request?id=request
// 主代码
export class Dwp_axios {
constructor(arg) {
this.createOption = Object.assign({
url: "",
header: {},
method: "GET",
timeout: 6000,
}, arg);
}
// 请求
dwp_axios = (option) => {
option = Object.assign(this.createOption, option);
return new Promise(async (resolve, reject) => {
let request = this.dwp_axios_before(option);
console.log(request)
try {
let response = {
request,
data: await uni.request(request) // 请求
}
resolve(this.dwp_axios_after(response));
} catch (e) {
console.log(e);
reject(e);
}
})
}
// 请求 守卫 前
dwp_axios_before = (config) => {
return config
}
// 请求 守卫 后
dwp_axios_after = (config) => {
return config
}
// get 请求
$get = (url, data) => {
return new Promise(async (resolve, reject) => {
try {
resolve(await this.dwp_axios({
url,
method: "GET",
data
}))
} catch (e) {
reject(e);
}
})
}
// post 请求
$post = (url, data) => {
return new Promise(async (resolve, reject) => {
try {
resolve(await this.dwp_axios({
url,
method: "POST",
data
}))
} catch (e) {
reject(e);
}
})
}
}
使用
import {
Dwp_axios
} from "./dwp-axios.js"
let request = new Dwp_axios();
// 请求守卫 前 使用 请求守卫 后 也同样的使用
request.dwp_axios_before = function(config) {
console.log("request", config);
config.header["myToken"] = "hello";
return config;
}
request.dwp_axios_after = function(config) {
console.log("response", config);
return config;
}
// 请求例子
request.dwp_axios({
url: "http://127.0.0.1:3000/logs/get",
method: "POST"
}).then(res => {
console.log(res);
});
request.$post("http://127.0.0.1:3000/logs/get", {name: 'dwp'}).then(res => {
console.log(res);
});
request.$get("http://127.0.0.1:3000/logs/get", {name: 'dwp'}).then(res => {
console.log(res);
});