vueaxios的封装
// 对http请求进行封装
import axios from 'axios'
// 使用自定义的配置文件发送请求
const instance = axios.create({
baseURL: '',
timeout: 5000,
headers: {
}
});
// 添加请求拦截器
instance.interceptors.request.use(function (config) {
// 在发送请求之前做些什么
return config;
}, function (error) {
// 对请求错误做些什么
return Promise.reject(error);
});
// 添加响应拦截器
instance.interceptors.response.use(function (response) {
// 对响应数据做点什么
if(response.status === 200){
return response;
}else{
console.error("请求错误")
console.error(response)
}
return response;
}, function (error) {
// 对响应错误做点什么
return Promise.reject(error);
});
export default instance
小程序request的封装
function request(options) {
// 请求拦截器
// ...
// 1. 加一些统一的参数,或者配置
if (!options.url.startsWith("https://") && !options.url.startsWith("http://")) {
options.url = "https://showme2.myhope365.com" + options.url
}
// 默认的请求头
let header = {
"cookie": wx.getStorageSync("cookie") || "",
"content-type": "application/x-www-form-urlencoded",
};
if (options.header) {
header = {
...header,
...options.header
}
}
return new Promise((reslove, reject) => {
// 调用接口
wx.request({
// 默认的配置
// 加载传入的配置
...options,
header,
success(res) {
// 响应拦截器,所有接口获取数据之前,都会先执行这里
// 1. 统一的错误处理
if (res.statusCode != 200) {
wx.showToast({
title: '服务器异常,请联系管理员',
})
}
reslove(res)
},
fail(err) {
reject(err)
}
})
})
}
export function get(url, options = {}) {
return request({
url,
...options
})
}
export function post(url, data, options = {}) {
return request({
url,
data,
method: "POST",
...options
})
}
uni-app的封装
// 代码块
// 封装的目的
// 1. 发送请求的时候调用更简洁
// 2. 添加一些通用的配置(超时时间,请求头)。 调用者没有传入配置的时候用默认的,调用者传入了相同,优先使用调用者
// 3. 改成使用promise解决异步问题
// 4. 统一维护域名
// 5. 添加请求拦截器,在所有请求之前加一些通用的操作
// 6. 代码响应之前,进行一些通用的操作
const proxy = {
"/course": {
target: "http://course.myhope365.com",
pathRewrite: '^/course'
}
}
/// 作用: 根据当前的url和代理得到完整url
// 输入: 当前的url
// 输出: 完整的url
function getUrl(url) {
for (let key in proxy) {
if (url.startsWith(key)) {
// 匹配到了代理
if (proxy[key].pathRewrite) {
// 需要进行前缀重写
url = url.replace(new RegExp(proxy[key].pathRewrite), "")
}
url = proxy[key].target + url
break;
}
}
///返回处理后的url
return url;
}
function getHeader(header = {}) {
return {
"Content-Type": "application/x-www-form-urlencoded",
// #ifndef H5
"Cookie": uni.getStorageSync("cookie"),
// #endif
...header
}
}
function request(options) {
return new Promise((reslove, reject) => {
if (!options.header) options.header = {}
const header = getHeader(options.header);
// 请求之前进行一些操作
// 加载代理
// #ifndef H5
options.url = getUrl(options.url)
// #endif
uni.request({
// 设置超时时间10s
timeout: 10000,
...options,
header,
success(res) {
// 响应之前进行一些操作
reslove(res)
},
fail(err) {
reject(err)
}
})
})
}
export function get(url, options) {
return request({
url,
...options,
method: "GET"
})
}
export function post(url, data, options) {
return request({
url,
data,
...options,
method: "POST"
})
}