In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
今天小编给大家分享一下Vue怎么封装axios的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以分享这篇文章给大家参考一下,希望大家阅读完这篇文章后有所收获,下面我们一起来了解一下吧。
安装axios
起手安装axios
npm install axios
request.js
该文件中对axios进行封装
import axios from 'axios'
const baseURL = 'http://localhost:4000/api'
// 创建 axios 实例
const service = axios.create({
baseURL: baseURL, // 请求地址前缀,将自动加在 url 前面
timeout: 6000 // 请求超时时间
})
// axios请求拦截器
service.interceptors.request.use(config => {
if (localStorage.getItem('loginToken')) {
// 请求统一设置header
config.headers.Authorization = localStorage.getItem('loginToken')
}
return config
}, error => {
return Promise.reject(error)
})
// axios响应拦截器
service.interceptors.response.use(response => {
return response.data
}, error => {
// console.log('看一看', error.response)
const { status } = error.response
if (status === 401) { // token失效
Message.error('token失效,请重新登录')
// 清除token
localStorage.removeItem('loginToken')
router.push('/')
}
return Promise.reject(error)
})
export { service as axios }
在axios.create操作中还可以进行其他的一些操作,诸如:
根据当前环境切换不同的url(生产环境/开发环境/测试环境)
baseURL: process.env.NODE_ENV === 'production' ? 'productApi': 'developApi'
1
统一请求头配置
headers: {
get: {
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
// 在开发中,一般还需要单点登录或者其他功能的通用请求头,可以一并配置进来
},
post: {
'Content-Type': 'application/json;charset=utf-8'
// 在开发中,一般还需要单点登录或者其他功能的通用请求头,可以一并配置进来
}
},
跨域、响应码处理
提供是否允许跨域的属性--withCredentials: true/false
请求响应序列化
// 在向服务器发送请求前,序列化请求数据
transformRequest: [function (data) {
data = JSON.stringify(data)
return data
}],
// 在传递给 then/catch 前,修改响应数据
transformResponse: [function (data) {
if (typeof data === 'string' && data.startsWith('{')) {
data = JSON.parse(data)
}
return data
}]
同样,拦截器中也可以自定义更多的内容
api.js
import { axios } from './request'
const api = {
user: '/user/getUsers'
}
export default api
export function getUsersApi(param) {
return axios({
url: api.user,
method: 'post',
data: param
})
}
以上就是"Vue怎么封装axios"这篇文章的所有内容,感谢各位的阅读!相信大家阅读完这篇文章都有很大的收获,小编每天都会为大家更新不同的知识,如果还想学习更多的知识,请关注行业资讯频道。
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.