vue中使用axios时封装公共方法(响应拦截器,请求拦截器)
npm install axios --save
//安装依赖
与main.js平行处创建http.js文件
import axios from 'axios'
axios.defaults.timeout = 60000; //响应时间
//配置请求头
axios.defaults.headers = {
//公共请求头配置
'属性':'这是是公共请求头的配置'
}
axios.defaults.baseURL = ''; //配置接口地址
//POST传参序列化(添加请求拦截器)
axios.interceptors.request.use((config) => {
//在发送请求之前做某件事
if(config.method === 'get'){
config.data = true;
}
if(sessionStorage.getItem('token')){
let token = sessionStorage.getItem('token')
//已经登录
config.headers['Content-Type'] = 'application/json;charset=UTF-8';
config.headers['鉴权属性'] = token;
}
return config;
},(error) =>{
// console.log('错误的传参')
return Promise.reject(error);
});
//返回状态判断(添加响应拦截器)
axios.interceptors.response.use((res) =>{
//对响应数据做些事
if(!res.data.success){
return Promise.resolve(res);
}
return res;
}, (error) => {
if(error.response.status == 401){
//授权过期
location.href = '/login'
}
return Promise.reject(error);
});
//返回一个Promise(发送post请求)
export function fetchPost(url, params,config) {
return new Promise((resolve, reject) => {
axios.post(url, params,config)
.then(response => {
resolve(response);
}, err => {
reject(err);
})
.catch((error) => {
reject(error)
})
})
}
返回一个Promise(发送get请求)
export function fetchGet(url,config, param) {
return new Promise((resolve, reject) => {
axios.get(url, config,{params: param})
.then(response => {
resolve(response)
}, err => {
reject(err)
})
.catch((error) => {
reject(error)
})
})
}
export default {
fetchPost,
fetchGet,
}
在main.js中引入
import { fetchPost,fetchGet } from './http.js'
Vue.prototype.getHttp = fetchGet;
Vue.prototype.postHttp = fetchPost;
在组件中调用
this.getHttp(url,config, param:{传值})
this.getHttp(this.url,{params:{id:this.id}}).then((res)=>{}).catch((err)=>{})
this.postHttp(url,params,config) params为传值
this.postHttp(this.url,{id:this.id}).then((res)=>{}).catch((err)=>{})
config为配置单独的header
传入格式
{
header:{
配置项
}
}
还没有评论,来说两句吧...