在本章中,我们将深入探讨如何使用 Axios 创建和管理实例。这将帮助我们更好地理解如何为不同的请求配置默认值,并通过实例来处理各种复杂的场景。
Axios 实例的创建
Axios 实例允许我们为特定的请求或一组请求设置自定义配置。这包括但不限于默认的请求方法、基础 URL、验证器等。首先,我们需要了解如何创建一个 Axios 实例。
const instance = axios.create({
baseURL: 'https://api.example.com',
timeout: 1000,
headers: {'X-Custom-Header': 'foobar'}
});在这个例子中,我们创建了一个 Axios 实例,并设置了基础 URL、请求超时时间和一个自定义头部。
使用 Axios 实例发起请求
一旦我们创建了 Axios 实例,就可以使用它来发起 HTTP 请求。这些请求的方式与全局 Axios 对象类似,但它们会继承我们在实例创建时指定的配置。
GET 请求
instance.get('/data')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});POST 请求
// www.javascriptcn.com code example
instance.post('/data', {
firstName: 'Fred'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});Axios 实例的配置选项
baseURL
baseURL 是一个字符串,用于设置所有请求的默认基础 URL。如果请求 URL 不是绝对路径,Axios 将自动将其附加到 baseURL 后面。
timeout
timeout 用于设置请求的超时时间(毫秒)。如果请求在指定时间内没有完成,它将被取消。
headers
headers 允许我们设置请求头。这可以是一个对象,其中键是头部名称,值是头部值。
auth
auth 用于提供 HTTP 认证信息。它应该是一个包含 username 和 password 属性的对象。
axios.create({
auth: {
username: 'janedoe',
password: 's00pers3cret'
}
});params
params 用于设置 URL 查询参数。这对于需要在 URL 中传递额外数据的 GET 请求特别有用。
// www.javascriptcn.com code example
axios.get('/user', {
params: {
ID: 12345
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});data
data 用于发送请求体数据,适用于 POST、PUT 等需要请求体的请求。
// www.javascriptcn.com code example
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});Axios 实例中的错误处理
在使用 Axios 实例发起请求时,错误处理非常重要。Axios 会根据请求的状态返回不同类型的错误。我们可以使用 .catch() 方法来捕获这些错误,并根据需要进行处理。
// www.javascriptcn.com code example
instance.get('/data')
.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);
});以上就是在 Axios 中使用实例的详细介绍。通过创建 Axios 实例并配置适当的选项,我们可以更灵活地管理 HTTP 请求,并且能够更好地处理各种请求相关的错误。希望这些内容对你有所帮助!