vue中axios 配置请求拦截功能 及请求方式如何封装

2023-05-24,,

main.js 中:

import axios from '................/axios'

axios.js 中:

//axios.js
import Vue from 'vue'
import axios from 'axios'
Vue.prototype.$http = axios //http request 封装请求拦截
axios.interceptors.request.use(config => {
// console.log("request")
// console.log(config) //请求方式
let method = config.method.toLowerCase();
if (method === 'get' || method === 'delete') {
Object.assign(config.params, {
"test": "testVAl"
});
}
return config;
}, error => {
return Promise.reject(err);
}); //http response 封装后台返回拦截器
axios.interceptors.response.use(response => {
// console.log(response)
//当返回信息为未登录或者登录失效的时候重定向为登录页面
// if (response.data.code == 'W_100004' || response.data.message == '用户未登录或登录超时,请登录!') {
// router.push({
// path: "/",
// querry: {
// redirect: router.currentRoute.fullPath
// } //从哪个页面跳转
// })
// }
if (typeof response.data === 'string') {
return JSON.parse(response.data);
} else {
return response;
}
}, error => {
return Promise.reject(error)
});

使用:

this.$http.get('/api/......', {params:{}}).then(res => {
console.log(res)
}, res => {
// error callback
});

vue中axios 配置请求拦截功能 及请求方式如何封装的相关教程结束。

《vue中axios 配置请求拦截功能 及请求方式如何封装.doc》

下载本文的Word格式文档,以方便收藏与打印。