主要目的就是简化整个项目的请求方式,封装请求可以很大程度的减少重复代码的编写,简化代码结构,特别是需要请求头的情况下,作用是很大的,方便后期的维护,也可以对请求结果做一些统一处理
当然为了代码更加简便,最好是将API接口也进行统一的管理,首先这样方便接口的调整,再者后期修改接口也不用,在页面中去找,一旦代码较多就很难处理
这里我主要说一下这个请求拦截器:
1、普通的GET,POST请求封装
- 请求封装
// import store from '../store/index.js' 需要使用store缓存中的内容,可以进行导入
const baseUrl = '' //请求接口地址
const httpRequest = (url, method, data) => {
let meth = method.toUpperCase();//小写改为大写
if (!data) {
data = {}
}
//if(getApp().globalData.token){
// data['token'] = getApp().globalData.token; //token
//}
console.debug(store.state.uerInfo.token)
let httpDefaultOpts = {
url: baseUrl + url,
data: data,
method: meth,
header: {
'content-type': 'application/x-www-form-urlencoded',
'Authorization':'请求token'
},
dataType: 'json',
}
return new Promise(function(resolve, reject) {
uni.request(httpDefaultOpts).then(
(res) => {
switch(res[1].data.code){
//成功返回
case 200: {
resolve(res[1])
break;
};
// token过期
case 401: {
uni.clearStorage();
uni.showModal({
title: '提示',
content: res[1].data.data.detail,
showCancel: false,
success: (res) => {
if(res.confirm){
uni.reLaunch({
url:'/pages/login/login'
})
}
}
})
break;
};
//错误信息
default :{
uni.showToast({
title:res[1].data.data.detail,
icon:'none'
})
//resolve(res[1]) //错误信息返不返回 看个人情况
break;
}
}
}
).catch(
(response) => {
reject(response)
}
)
})
};
export default {
baseUrl,
httpRequest
}
- main.js中全局导入
import http from './utils/req.js'
Vue.prototype.http = http;
- vue界面中使用
this.http.httpRequest(请求地址,'请求方式',参数).then(res => {
处理返回值
})
2、包含PATCH请求方式的请求封装
已知官方提供的uni.request是不提供patch的,但是为了安全我们的接口经常还是会使用到patch的方式,以下是解决方案,亲测可用
- 页面中的使用,为了简化代码也可以将共同的部分提出来进行全局引入,比如说headers部分,下面是没有全局使用的
import axios from 'axios'
const requests = axios.create({
headers: {
'content-type': 'application/x-www-form-urlencoded',
'Authorization':'Bearer '+ this.uerInfo.token
},
})
requests.patch(this.$api.update_partial_update+this.id+'/')
.then(function(res){
if(res.data.code==200){
uni.showModal({
title: '提示',
content: '当前订单已确认',
success: (res) => {
if (res.confirm) {
uni.redirectTo({
url:'/pages/work-detail/work-1/workpage'
})
}
}
})
}
})
.catch(function(err){
alert(err);
})
- 如果要适用于手机端,一定要加上下面适配器的代码👇,如果需要同时适配网页端和手机端,可以加入// #ifdef … 来进行代码的适配:
# 手机端适配器,如果手机端使用一定要加上这段代码
axios.defaults.adapter = function (config) {
return new Promise((resolve, reject) => {
console.log(config)
var settle = require('axios/lib/core/settle');
var buildURL = require('axios/lib/helpers/buildURL');
uni.request({
method: config.method.toUpperCase(),
url: buildURL(config.url, config.params, config.paramsSerializer),
header: config.headers,
data: config.data,
dataType: config.dataType,
responseType: config.responseType,
sslVerify: config.sslVerify,
complete:function complete(response){
response = {
data: response.data,
status: response.statusCode,
errMsg: response.errMsg,
header: response.header,
config: config
};
settle(resolve, reject, response);
}
})
})
}
本文介绍了一种封装HTTP请求的方法,旨在简化项目中的请求流程,减少代码冗余,便于维护和错误处理。同时,讨论了API接口统一管理的重要性,以及如何通过请求拦截器和补丁请求方式增强安全性。

389

被折叠的 条评论
为什么被折叠?



