Axios是一个基于Promise的HTTP客户端,用于浏览器和node.js环境,可以发送异步HTTP请求到REST端点并处理响应。以下是Axios的基本用法和常用方法:
Axios的基本用法
-
安装Axios
如果你还没有安装Axios,可以通过npm、yarn或其他包管理工具进行安装。例如,使用npm安装Axios的命令如下:
npm install axios
或者使用yarn:
yarn add axios
-
引入Axios
在你的项目中,你可以通过
import
或require
语句来引入Axios。例如,在ES6模块中:import axios from 'axios';
或者在CommonJS模块中:
const axios = require('axios');
-
发送请求
Axios支持多种请求方式,如GET、POST、PUT、DELETE等。以下是一些示例:
-
GET请求:
axios.get('/user?ID=12345') .then(function (response) { // 处理成功情况 console.log(response);
}) .catch(function (error) {
// 处理错误情况
console.log(error); }) .then(function () {
// 总是会执行
});
// 或者使用
axios(config) axios({
method: 'get', url: '/user?ID=12345',
}) .then(function (response) {
console.log(response);
}) .catch(function (error) {
console.log(error);
});
-
POST请求:
axios.post('/user', {
firstName: 'Fred', lastName: 'Flintstone'
}) .then(function (response) {
console.log(response);
}) .catch(function (error) {
console.log(error);
});
-
- PUT请求:
-
axios.put('/user/12345', {
firstName: 'John', lastName: 'Doe'
}) .then(function (response) {
console.log(response);
}) .catch(function (error) {
console.log(error);
});
-
-
DELETE请求:
axios.delete('/user/12345') .then(function (response) {
console.log(response);
}) .catch(function (error) {
console.log(error);
});
-
Axios的常用配置项
- url:请求的URL。
- method:请求方法,如GET、POST、PUT、DELETE等。
- headers:请求头,可以设置自定义的请求头信息。
- params:URL查询参数,适用于GET、DELETE请求。
- data:作为请求主体被发送的数据,适用于POST、PUT、PATCH请求。
- timeout:请求超时的毫秒数,如果请求耗时超过这个时间,请求将被中断。
- baseURL:自动加在
url
前面的基础URL,除非url
是一个绝对URL。 - transformRequest:允许在向服务器发送前修改请求数据,只能用于PUT、POST和PATCH请求。
- transformResponse:在传递给
.then
或.catch
之前,允许修改响应数据。
拦截器
Axios提供了请求拦截器和响应拦截器,允许你在请求或响应被then
或catch
处理之前拦截它们。
-
请求拦截器:
axios.interceptors.request.use(function (config) {
// 在发送请求之前做些什么 return config;
}, function (error) {
// 对请求错误做些什么
return Promise.reject(error);
});
-
响应拦截器:
axios.interceptors.response.use(function (response) {
// 对响应数据做点什么
return response;
}, function (error) { // 对响应错误
-