您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
# Vue.js中Axios用法是怎样的
## 一、Axios简介与核心特性
Axios是一个基于Promise的HTTP客户端,专门用于浏览器和Node.js环境。在Vue.js项目中,它成为处理HTTP请求的首选方案,主要优势包括:
1. **Promise API** - 天然支持异步操作链式调用
2. **请求/响应拦截** - 可全局处理HTTP流程
3. **自动JSON转换** - 智能处理JSON数据
4. **客户端XSRF防护** - 内置安全机制
5. **取消请求** - 支持AbortController
6. **多环境支持** - 浏览器和Node.js通用
## 二、基础安装与配置
### 1. 安装Axios
通过npm或yarn安装:
```bash
npm install axios
# 或
yarn add axios
在main.js中全局引入:
import axios from 'axios'
Vue.prototype.$http = axios
创建自定义实例:
const api = axios.create({
baseURL: 'https://api.example.com',
timeout: 5000,
headers: {'X-Custom-Header': 'foobar'}
})
// 基础形式
axios.get('/user?ID=12345')
// 参数对象形式
axios.get('/user', {
params: {
ID: 12345
}
})
// async/await用法
async getUser() {
try {
const response = await axios.get('/user/12345')
console.log(response.data)
} catch (error) {
console.error(error)
}
}
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
// 指定Content-Type
axios.post('/user', data, {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
function getUserAccount() {
return axios.get('/user/12345')
}
function getUserPermissions() {
return axios.get('/user/12345/permissions')
}
Promise.all([getUserAccount(), getUserPermissions()])
.then(([acct, perm]) => {
// 两个请求都完成后执行
})
// 请求拦截
axios.interceptors.request.use(config => {
config.headers.Authorization = localStorage.getItem('token')
return config
}, error => {
return Promise.reject(error)
})
// 响应拦截
axios.interceptors.response.use(response => {
return response.data // 直接返回data部分
}, error => {
if (error.response.status === 401) {
router.push('/login')
}
return Promise.reject(error)
})
const CancelToken = axios.CancelToken
let cancel
axios.get('/user/12345', {
cancelToken: new CancelToken(function executor(c) {
cancel = c
})
})
// 取消请求
cancel()
const formData = new FormData()
formData.append('file', fileInput.files[0])
axios.post('/upload', formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
})
创建api.service.js
:
export default {
getUsers() {
return axios.get('/users')
},
createUser(data) {
return axios.post('/users', data)
}
}
import api from '@/services/api.service'
export default {
data() {
return {
users: []
}
},
async created() {
try {
const res = await api.getUsers()
this.users = res.data
} catch (err) {
this.$toast.error('获取用户列表失败')
}
}
}
// store/actions.js
actions: {
async fetchUsers({ commit }) {
try {
const { data } = await axios.get('/users')
commit('SET_USERS', data)
} catch (error) {
commit('SET_ERROR', error.message)
}
}
}
配置代理(vue.config.js):
module.exports = {
devServer: {
proxy: {
'/api': {
target: 'http://other-server.com',
changeOrigin: true,
pathRewrite: {
'^/api': ''
}
}
}
}
}
axios.defaults.xsrfCookieName = 'csrftoken'
axios.defaults.xsrfHeaderName = 'X-CSRFToken'
创建错误处理拦截器:
axios.interceptors.response.use(null, error => {
if (!error.response) {
// 网络错误
showNotification('网络连接异常')
} else {
const status = error.response.status
const errorMap = {
400: '请求参数错误',
401: '未授权,请登录',
403: '拒绝访问',
404: '资源不存在'
}
showNotification(errorMap[status] || `服务器错误:${status}`)
}
return Promise.reject(error)
})
_.throttle
对于TypeScript项目,可以添加类型定义:
interface User {
id: number
name: string
}
axios.get<User>('/user/1')
.then(response => {
console.log(response.data.name) // 自动推断类型
})
特性 | Axios | Fetch API | jQuery.ajax |
---|---|---|---|
浏览器兼容性 | 良好 | 较新浏览器 | 广泛 |
Promise支持 | ✅ | ✅ | ❌ |
拦截器 | ✅ | ❌ | ❌ |
取消请求 | ✅ | ✅(Abort) | ✅ |
自动JSON转换 | ✅ | ❌ | ✅ |
Axios在Vue.js生态中提供了完善的HTTP解决方案,通过: - 简洁的API设计 - 强大的拦截器机制 - 完善的错误处理 - 良好的TypeScript支持
使其成为Vue项目中进行网络请求的首选工具。建议结合项目实际情况进行适当封装,既能保持灵活性,又能提高代码复用率。 “`
(全文约1800字,实际字数可能因格式略有差异)
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。