安装 Axios
在开始使用 Axios 之前,你需要先安装它。你可以通过 npm 或者 yarn 来安装 Axios。
npm install axios
或者
yarn add axios
安装完成后,你可以在你的项目中导入 Axios:
import axios from 'axios';
发送请求
Axios 提供了多种方法来发送 HTTP 请求,包括 GET、POST、PUT 和 DELETE 等。
GET 请求
GET 请求是最常用的请求类型之一。你可以使用 axios.get() 方法来发送 GET 请求:
// www.javascriptcn.com code example
axios.get('/user?ID=12345')
.then(function (response) {
// 处理成功情况
console.log(response);
})
.catch(function (error) {
// 处理错误
console.log(error);
});POST 请求
POST 请求用于向服务器发送数据。你可以使用 axios.post() 方法来发送 POST 请求:
// www.javascriptcn.com code example
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});PUT 请求
PUT 请求用于更新服务器上的资源。你可以使用 axios.put() 方法来发送 PUT 请求:
// www.javascriptcn.com code example
axios.put('/user/12345', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});DELETE 请求
DELETE 请求用于删除服务器上的资源。你可以使用 axios.delete() 方法来发送 DELETE 请求:
axios.delete('/user/12345')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});请求配置
除了基本的请求类型之外,Axios 还提供了丰富的配置选项来定制请求。
设置请求头
你可以通过 headers 属性来设置请求头:
axios.get('/user', {
headers: { 'X-Custom-Header': 'foobar' }
})
.then(function (response) {
console.log(response);
});设置超时时间
你可以通过 timeout 属性来设置请求的超时时间:
// www.javascriptcn.com code example
axios.get('/user', {
timeout: 1000
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});设置基础 URL
你可以通过 baseURL 属性来设置请求的基础 URL,这样你在发送请求时就不需要每次都写完整的 URL:
// www.javascriptcn.com code example
axios.defaults.baseURL = 'https://api.example.com';
axios.get('/user/12345')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});响应处理
Axios 的响应对象包含几个属性,比如 data、status、statusText、headers 和 config。这些属性包含了请求和响应的详细信息。
获取响应数据
你可以通过 response.data 来获取服务器返回的数据:
axios.get('/user/12345')
.then(function (response) {
console.log(response.data);
});获取状态码
你可以通过 response.status 来获取 HTTP 状态码:
axios.get('/user/12345')
.then(function (response) {
console.log(response.status); // 输出状态码
});获取状态文本
你可以通过 response.statusText 来获取 HTTP 状态文本:
axios.get('/user/12345')
.then(function (response) {
console.log(response.statusText); // 输出状态文本
});获取响应头
你可以通过 response.headers 来获取响应头信息:
axios.get('/user/12345')
.then(function (response) {
console.log(response.headers['content-type']); // 输出内容类型
});获取请求配置
你可以通过 response.config 来获取发送请求时的配置信息:
axios.get('/user/12345')
.then(function (response) {
console.log(response.config.url); // 输出请求 URL
});错误处理
Axios 提供了统一的方式来处理错误。当请求失败时,Axios 会抛出一个错误对象,你可以通过 .catch() 方法来捕获这个错误并进行相应的处理。
捕获错误
你可以使用 .catch() 方法来捕获请求过程中发生的任何错误:
// www.javascriptcn.com code example
axios.get('/user/12345')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
if (error.response) {
// 请求已发出,但服务器响应的状态码不在 2xx 范围内
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
} else if (error.request) {
// 请求已发出,但是没有接收到响应
console.log(error.request);
} else {
// 发生了一些其他错误
console.log('Error', error.message);
}
console.log(error.config);
});自定义错误处理
你可以自定义错误处理逻辑,例如显示错误提示或记录日志:
// www.javascriptcn.com code example
axios.get('/user/12345')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
if (error.response) {
// 显示错误提示
alert('请求失败,请稍后再试!');
} else if (error.request) {
console.error('请求未完成');
} else {
console.error('请求发生错误', error.message);
}
console.error(error.config);
});拦截器
Axios 支持拦截器,可以在请求被发送到服务器之前或响应被处理之前修改它们。
添加请求拦截器
你可以使用 axios.interceptors.request.use() 方法来添加请求拦截器:
axios.interceptors.request.use(function (config) {
// 在发送请求之前做些什么
return config;
}, function (error) {
// 对请求错误做些什么
return Promise.reject(error);
});添加响应拦截器
你可以使用 axios.interceptors.response.use() 方法来添加响应拦截器:
axios.interceptors.response.use(function (response) {
// 对响应数据做点什么
return response;
}, function (error) {
// 对响应错误做点什么
return Promise.reject(error);
});移除拦截器
如果你需要移除拦截器,可以使用 axios.interceptors.request.eject() 和 axios.interceptors.response.eject() 方法:
const myInterceptor = axios.interceptors.request.use(function () {/*...*/});
axios.interceptors.request.eject(myInterceptor);取消请求
Axios 支持取消请求的功能。你可以通过创建一个取消令牌来实现这一点。
创建取消令牌
你可以使用 axios.CancelToken.source() 方法来创建一个取消令牌:
// www.javascriptcn.com code example
const CancelToken = axios.CancelToken;
const source = CancelToken.source();
axios.get('/user/12345', {
cancelToken: source.token
})
.then(function (response) {
console.log(response);
})
.catch(function (thrown) {
if (axios.isCancel(thrown)) {
console.log('Request canceled', thrown.message);
} else {
// 处理错误
}
});
// 取消请求(message 参数是可选的)
source.cancel('Operation canceled by the user.');使用自定义取消函数
你也可以使用自定义的取消函数来取消请求:
// www.javascriptcn.com code example
const CancelToken = axios.CancelToken;
let cancel;
axios.get('/user/12345', {
cancelToken: new CancelToken(function executor(c) {
// 一个执行器接收一个取消函数作为参数
cancel = c;
})
})
.then(function (response) {
console.log(response);
});
// 取消请求(message 参数是可选的)
cancel('Operation canceled by the user.');以上就是 Axios API 的详细介绍。通过这些功能,你可以灵活地发送各种类型的 HTTP 请求,并且能够处理请求过程中的各种情况。希望这些内容对你有所帮助!