發送 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);
});