vue axios/uniapp 简单的请求(拦截)封装示例
axiosnpm 下载 axios新建http.js(随意)import axios from 'axios';import qs from'qs';// const baseUrl = '';//配置接口地址const baseUrl =''//线上//添加请求拦截器axios.interceptors.request.use((config) => {//在发送请求之前做某件事//...
·
uniapp
- 可以新建一个api.config.js
const BASR_URL = 'www.baidu.com';
const IMG_BASE_URL = 'www.baidu.com';
const API_CONFIG = {
login: '',
};
export {
API_CONFIG,
BASR_URL,
IMG_BASE_URL
}
- request.js
// 包含刷新token代码比较繁琐,可以自行优化
import {
API_CONFIG,
BASR_URL
} from './api.config.js';
import {
getToken,
setStorage,
Toast
} from './tool.js';
let pendings = [];
const myHttp = (options) => {
return new Promise((resolve, reject) => {
uni.request(createRequest(options, resolve, reject))
})
};
const request = (options, resolve, reject) => {
uni.request(createRequest(options, resolve, reject))
};
const createRequest = (options, resolve, reject) => {
let param = dealRequestParams(options),
resObj = {
success: res => {
if (res.statusCode == 200) {
if (res.data.code == -1) {
//刷新token保持登录状态
if (res.data.msg == '会话失效,请重新登录') {
pendings.push([options, resolve, reject]);
updateToken();
}
} else {
resolve(res.data);
}
} else {
}
},
fail: err => {
reject(err)
}
};
return Object.assign(param, resObj)
};
const dealRequestParams = (options) => {
let url = options.url ? options.url : API_CONFIG[options.api],
token = getToken(),
header = {
'content-type': 'application/x-www-form-urlencoded;charset=utf-8',
token
};
options.method = options.method ? options.method.toUpperCase() : 'GET';
return {
url: BASR_URL + url,
method: options.method,
data: options.data || {},
header: options.header || header
}
};
const eachpendings = () => {
if (pendings.length) {
pendings.forEach(async item => {
await request(...item);
await pendings.shift();
});
};
};
// 刷新token
const updateToken = () => {
uni.login({
provider: 'weixin',
success(loginRes) {
let code = loginRes.code,
opts = {
api: 'refreshToken',
method: 'post',
data: {
wxcode:code
}
};
myHttp(opts).then(res => {
if (res.code == 1) {
let {
token
} = res.data;
setStorage('TOKEN', token);
eachpendings();
};
})
},
fail(e) {
}
})
};
export {
myHttp
}
// 调用
// 挂载到Vue.prototype
getData(){
let opts = {
api: 'login',
method: '',
data: {}
};
this.$http(opts).then();
// or
myHttp(opts).then();
},
axios
- npm 下载 axios
- 新建http.js(随意)
- 后端请求拼接方式统一
import axios from 'axios';
import qs from 'qs';
// const baseUrl = ''; //配置接口地址
const baseUrl =''//线上
//添加请求拦截器
axios.interceptors.request.use((config) => {
//在发送请求之前做某件事
//...
return config;
},(error) =>{
return Promise.reject(error);
});
//返回状态判断(添加响应拦截器)
axios.interceptors.response.use((res) =>{
//....
return res;
}, (error) => {
//.....
return Promise.reject(error);
});
//返回一个Promise(发送post请求)
const httpRequest = (sign,url,data,method) => {
let token = localStorage.getItem('token') || '';
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';
axios.defaults.headers.post['app-type']='webapp';
axios.defaults.headers.post['token']=token;
axios.defaults.headers.post['sign']=sign; //项目需要
let httpDefaultOpts = {
url: baseUrl+url,
data:data,
method: method,
}
let promise = new Promise(function(resolve, reject) {
axios(httpDefaultOpts).then(
(res) => {
resolve(res)
}
).catch(
(response) => {
reject(response)
}
)
})
return promise
};
export default {
httpRequest
}
- 后端请求拼接方式不统一
//接口配置文件
//实例数据
const devaddressUrl = 'devdownline'; //devdownline 开发 //devonline 生产
const requestConfig = {
baseUlr: devaddressUrl == 'devdownline' ? 'http://192.168.0.102/:8080' : 'www.baidu.com',
imgUrl: devaddressUrl == 'devdownline' ? 'http://192.168.0.102/:8080' : 'www.baidu.com',
login: 'sign/login'
};
//下面请求数据里的reqApi就是requestConfig对象的key reqApi:"login"
export { requestConfig };
import axios from 'axios';
import qs from 'qs';
import { requestConfig } from './configApi'; // 接口的配置文件
import { deCode } from '../../libs/ulits/tool'; // 解密在我别的文章里有介绍
axios.interceptors.request.use((config) => {
return config;
},(error) =>{
return Promise.reject(error);
});
axios.interceptors.response.use((res) =>{
return res;
}, (error) => {
return Promise.reject(error);
});
const httpRequest = (dataQuery,methods) => {
let token = localStorage.getItem('Authorization') ? deCode(localStorage.getItem('Authorization')) : '';
methods = methods || 'get';
axios.defaults.headers = {
'Content-Type' : 'application/json',
'token' : 'Bearer ' + token,
};
let httpDefaultOpts = {
url: requestConfig['baseUlr'] + requestConfig[dataQuery.reqApi],
data: dataQuery.data,
method: methods == 'post' ? 'post' : 'delete',
};
if(methods == 'get'){
//没有key的get方式 www.baidu.com/5
if(dataQuery.hasOwnProperty('type')){
let param = '';
for(let i in dataQuery.data){
param = dataQuery.data[i];
};
let promise = new Promise(function(resolve, reject) {
axios({
method:'get',
url: requestConfig['baseUlr'] + requestConfig[dataQuery.reqApi] + '/' + param,
})
.then(res => {
resolve(res);
})
.catch(err => {
reject(err.response)
})
});
return promise;
}else{
//正常的get方式 www.baidu.com/?id="5"
let promise = new Promise(function(resolve, reject) {
axios.get(httpDefaultOpts.url, {
params: httpDefaultOpts.data
})
.then(res => {
resolve(res);
})
.catch(err => {
reject(err.response)
})
});
return promise;
}
};
if(methods == 'post' || methods == 'delete'){
//正常的post和delete
let promise = new Promise(function(resolve, reject) {
axios(httpDefaultOpts).then(
(res) => {
resolve(res)
}
).catch(
(err) => {
reject(err.response)
}
)
})
return promise;
};
if(methods == 'deletehead'){
//不太正常的delete
//url www.baidu.com/5
//body [1,2,3]
let param = '';
for(let i in dataQuery.data.head){
param = dataQuery.data.head[i];
};
let promise = new Promise(function(resolve, reject) {
axios({
method:'delete',
url: requestConfig['baseUlr'] + requestConfig[dataQuery.reqApi] + '/' + param,
data: dataQuery.data.body,
})
.then(res => {
resolve(res);
})
.catch(err => {
reject(err.response)
})
});
return promise;
}
};
export {
httpRequest,
};
/*
*数据格式 => deletehead
*({
* reqApi:'123',
* data:{
* head:{
* formid:''
* },
* body:[1,2,3,]
* }
*},'deletehead')
*/
/*
*({
* reqApi:'123',
* data:{
*
* }
*},'post') => post || delete
*/
/*
*({
* reqApi:'123',
* data:{
*
* //www.baidu.com/5
* type:"slash" //需要
* }
*}) => get可以不用写
*/
uniapp
1.下载uni-request
2.import uniRequest from ‘…/components/uni-request’;
3.使用
uniRequest.defaults.baseURL = '地址';
// 请求拦截
uniRequest.interceptors.request.use(
request => {
//配置基本信息
return request;
},
err => {
return Promise.reject(err);
});
// 响应拦截
uniRequest.interceptors.response.use((res)=>{
<!--写你需要干什么-->
return Promise.resolve(res);
}, function(error) {
return Promise.reject(error);
});
const http = function(sign,url,data,token) { //简单写一下,基本和上面那个差不多
<!--以下添加的头仅供参考-->
uniRequest.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';
uniRequest.defaults.headers.post['token']=token;
uniRequest.defaults.headers.post['sign']=sign;
uniRequest.defaults.headers.post['app-type']='webapp';
return uniRequest.post(url,{data})
}
export default {
http,
}
- uniapp可以结合promise自己封装
const http = function(sign,url,data,token) {
let baseUrl = '请求地址';
let httpDefaultOpts = {
url: baseUrl + url,
data: {data},
method: "POST", //这里只写了一个POST请求,如果还有get或者别的,自己加一个判断,把method写成变量。
header: {
'content-type': 'application/x-www-form-urlencoded;charset=UTF-8',
'app-type': 'webapp',
'sign':sign, // 根据实际项目需求添加
'token':token, // 根据实际项目需求添加
}
}
return new Promise(function(resolve, reject) {
uni.request(httpDefaultOpts).then(
(res) => {
resolve(res[1])
}
).catch(
(response) => {
reject(response)
}
)
})
}
export default {
http,
}
- 如果需要结合vuex来做一些操作,import store from ‘…/store/index.js’; 就可以了。
上面的请求分装方式我贴的代码比较繁琐,可以参照根据实际的项目需求修改或增加就可以。觉得有什么不好的地方留言,一起进步。
更多推荐
已为社区贡献5条内容
所有评论(0)