发送 POST 请求
基本用法
axios.post('/api/login', {username: 'lcyyyy',password: '123456'
})
.then(response => {console.log('请求成功:', response.data);
})
.catch(error => {console.error('请求失败:', error);
});
在 Vue 组件中使用
export default {methods: {async submitForm() {try {const response = await axios.post('/api/submit', {name: this.name,email: this.email});console.log('提交成功:', response.data);} catch (error) {console.error('提交失败:', error.response?.data || error.message);}}}
}
处理请求参数
发送 JSON 数据(默认)
Axios 默认会将 JavaScript 对象序列化为 JSON,并自动设置请求头 Content-Type: application/json
。
发送表单数据(FormData)
如果需要提交表单格式数据(如文件上传),需使用 FormData
:
const formData = new FormData();
formData.append('file', this.file); // 文件对象
formData.append('comment', '这是一个文件');axios.post('/api/upload', formData, {headers: {'Content-Type': 'multipart/form-data' // Axios 会自动识别,可省略}
});
全局配置与拦截器
1全局默认配置
// main.js 或单独配置文件
axios.defaults.baseURL = 'https://api.example.com';
axios.defaults.timeout = 5000; // 超时时间
请求拦截器
axios.interceptors.request.use(config => {// 在发送请求前做些什么(如添加 token)config.headers.Authorization = `Bearer ${localStorage.getItem('token')}`;return config;
}, error => {return Promise.reject(error);
});
响应拦截器
axios.interceptors.response.use(response => {// 对响应数据做统一处理return response.data; // 直接返回核心数据
}, error => {// 统一处理错误(如 401 跳转登录页)if (error.response.status === 401) {router.push('/login');}return Promise.reject(error);
});