axios拦截器接口api请求 统一封装
程序员文章站
2022-07-04 09:37:47
第一、新建http.js第二、http.js代码import Axios from 'axios';const axios = Axios.create();let timer = nullimport { Message } from 'element-ui';/** * 提示函数 * 显示一秒后关闭 * @param handle 统一提示 * @param type 统一状态 */const tip = (type = 'error', handle) =>.....
第一、新建http.js
第二、http.js代码
import Axios from 'axios';
const axios = Axios.create();
let timer = null
import { Message } from 'element-ui';
/**
* 提示函数
* 显示一秒后关闭
* @param handle 统一提示
* @param type 统一状态
*/
const tip = (type = 'error', handle) => {
Message({
type,
message: handle,
});
};
/**
* 请求失败后的错误统一处理
* @param {Number} status 请求失败的状态码
*/
const errorHandle = (status, other) => { };
// 请求拦截器
axios.interceptors.request.use(
(config) => {
let obj = {}
if (JSON.parse(localStorage.getItem('ngsco_token'))) {
obj.Authorization = JSON.parse(localStorage.getItem('ngsco_token')).accessToken
}
//请求头里Authorization添加token
config.headers = {
'Content-Type': 'application/json;charset=UTF-8',
Accept: 'application/json, text/plain',
...obj
};
return config;
},
(error) => {
// 对请求错误做些什么
return Promise.reject(error);
}
);
// 响应拦截器
axios.interceptors.response.use(
// 请求成功
(res) => {
if (res.status === 200) {
//特殊处理authorization 如果有新的authorization 替换旧的token
if(res.headers.authorization) {
let date = JSON.parse(localStorage.getItem('ngsco_token'))
date.accessToken = res.headers.authorization
localStorage.setItem('ngsco_token',JSON.stringify(date))
}
return Promise.resolve(res);
} else {
return Promise.reject(res);
}
},
// 请求失败
(error) => {
const { response } = error;
if (response) {
//401token过期
if (response.status === 401) {
//防抖 token失效
if (timer) clearTimeout(timer)
timer = setTimeout(() => {
Message({
type: 'error',
message: 'token失效,重新登陆'
});
setTimeout(() => {
localStorage.removeItem('ngsco_token')
window.location.href = '/ngsoc/login'
}, 1000)
})
}
// 请求已发出,但是不在200的范围
return Promise.reject(response);
} else {
// 处理断网的情况
// eg:请求超时或断网时,更新state的network状态
// store.commit('changeNetwork', false);
}
}
);
export default axios;
3、定义接口api (新建一个js) 如图:
/**
* api接口的统一封装
*/
import request from '@/services/http';
/**
* @param {}
* 获取验证码
*/
export const getCaptcha = (query) => {
return request({ url: '/api/captcha', method: 'get',data: query})
}
/**
* 登陆
* @param { Object } params
*/
export const setSaveLogin = (params) => {
return request({ url: '/api/login', method: 'post', data: params })
}
/**
* 退出登陆
* @param { Object } params
*/
export const setOutLogin = (params) => {
return request({ url: '/api/logout', method: 'get', data: params })
}
4、调用接口
import * as service from "@/api/login/index"; //引入刚定义的api
const response = async() => {
const res = await service.setSaveLogin(params);
console.log(res,'res数据')
}
本文地址:https://blog.csdn.net/weixin_45515229/article/details/108979508