概述

Axios 是一个用于基于 Promise 的异步请求的 HTTP 库。它的 API 易于使用,可以在许多不同的环境中使用,包括 NodeJS(服务器端)和浏览器(客户端)。Axios 用于进行 REST API 调用,以在后端执行所需的操作并将数据提取到前端。它还具有内置的错误处理功能,有助于代码调试。该 API 与 React 和“Angular”等流行的前端库配合得很好,使其成为许多开发人员的首选。

什么是 Axios?

Axios 是世界上最受欢迎的 JavaScript 库之一。它是一个 HTTP 客户端,可用于从浏览器和 NodeJS 发出请求。它原生支持 Promise API,因为发出请求是一个异步过程。与 JavaScript 原生提取方法相比,Axios 以其易用性而闻名。

Axios 可用于从您最喜欢的前端库(如 React 或 Vue)获取数据。使用 REST API 等 API 在数据库上执行创建、读取、更新和删除等操作变得更加容易,Node.js 中的 Axios。Axios 还提供了其他有用的功能来处理 API 和请求。

为什么使用 Axios NPM 包?

Axios 比原生 fetch 方法更易于使用,因为方法定义得更明确。例如。Axios 中的 get() 方法告诉我们,我们正在发出 GET 请求,没有必要明确地明确请求方法。Axios 需要更少的代码行,因为它具有内置的 JSON 支持和解析。JSON 响应会自动转换为 JavaScript 对象,而在 fetch 方法中,需要使用 response.json() 手动转换它。若要在应用程序中使用响应数据,必须将 JSON 数据转换为 JavaScript 对象。我们可以从Node.js后端发送 HTTP 请求,从浏览器发送 XHR - XMLHTTPRequests。Axios 在错误处理方面提供了更好的体验。它有明确的错误消息和错误代码。这使得使用 Axios 调试应用程序变得更加容易。使用 Axios 可以轻松设置响应超时,因为它可以简单地将其添加为配置对象中的属性 timeout = 5000。如果我们要使用 fetch 方法实现此功能,那么我们需要使用 AbortController 接口,这需要手动初始化和调用。这增加了代码行数和复杂性,而在 Axios 中,它只是一行。

特征

紧凑的库,便于进行 HTTP 通信Axios 是一个基于 Promise 的库它可用于从 Node.js 发出 HTTP 请求,从浏览器发出 XHR 请求开箱即用的 JSON 解析使用错误消息和错误代码进行广泛的错误处理。我们可以轻松中止请求、取消请求以及设置请求超时。内置安全性,可防止会话骑行。向后兼容性。Axios 甚至支持 Internet Explorer!

浏览器支持

根据 Axios 的官方文档,根据其版本支持以下浏览器。对于 Axios,使用下面未提及的浏览器可能无法按预期工作。

浏览器版本支持 ( 是 / 否)Google Chrome最近的是的Firefox最近的是的Opera最近的是的Safari最近的是的Microsoft Edge最近的是的Internet Explorer11是的

如何使用 npm 包安装 Axios?

要使用“Node Package Manager”安装 Axios,请在 NodeJS 项目中运行以下命令:

npm 安装 axios

我们还可以使用内容分发网络链接在我们的 HTML 页面上使用 CDN:

Axios 入门

在本节中,我们将学习如何在Node.js中使用 Axios 发送各种 HTTP 请求。我们将对电子商务后端应用程序进行 REST API 调用,以执行以下操作:

GET - 获取一个类别中的所有产品,例如:所有手机POST - 在数据库中创建新产品PUT - 修改现有产品数据DELETE - 删除现有产品

发出 HTTP 请求 - 获取请求

为了向后端发出 get 请求,我们将使用以下代码片段:

const axios = require("axios")

//Request the list of products

axios.get('http://localhost:8080/ecommerce/getProducts')

.then(function (response) {

// if successful then log the response status and data

console.log(response.status);

console.log(response.data);

})

.catch(function (error) {

// if not successful then log the error

console.log(error);

})

.finally(function () {

// always executed

});

上述代码向本地后端服务器发出 get 请求,并将状态码和响应数据记录到控制台。

这是输出:(仅显示一长串产品中的几个)

状态代码为 200,表示成功获取数据。响应数据是一个对象。这是一个解析为 JS 对象的 JSON 对象,并具有一个带有 product 对象数组的数据键。

发出 HTTP 请求 - 发布请求

以下是向后端发送 POST 请求的代码片段:

const axios = require("axios")

// Request for creating a new product

axios.post('http://localhost:8080/ecommerce/postProducts', {

name: 'Apple Iphone 11',

description: 'Previous generation mobile from Apple,

cost: 50000,

categoryId: 5

})

.then(function (response) {

console.log(response.data);

})

.catch(function (error) {

console.log(error);

});

以下是我们收到的回复:

发出 HTTP 请求 - 删除请求

现在让我们尝试删除其中一个产品。这是删除的代码片段。请注意,我们已经稍微切换了语法以显示 async-await 功能:

// async function

const deleteProduct = async () => {

try {

// using async-await to delete the data from the URL

const response = await axios.delete('http://8080/ecommerce/deleteProduct/3')

console.log(response.data);

} catch ( err ){

if(err.response){

console.log(err.response.status);

console.log(err.response.statusText);

console.log(err.response.data);

}

}

}

deleteProduct()

这里我们删除了 id = 3 的产品。

以下是控制台中的输出:

发出 HTTP 请求 - Put 请求

最后,我们将尝试在后端更新数据库中的现有数据。以下是相同的代码片段:

axios.put('http://localhost:8080/ecommerce/updateProduct/1', {

name: 'Samsung Galaxy 11',

description: 'Previous generation mobile from Samsung',

cost: 50000,

categoryId: 5

})

.then(function (response) {

console.log(response.data);

})

.catch(function (error) {

console.log(error);

});

在这里,我们使用对象中的数据更新 id = 1 的产品。 以下是控制台中的输出:

因此,我们已经成功地使用 Axios 在Node.js中进行了所有主要的 REST API 调用,即 GET、POST、DELETE 和 PUT 请求。

Axios 接口

在本节中,我们将学习如何在Node.js中使用 Axios 进行显式配置。

我们可以创建一个配置对象并将该对象传递给 Axios 方法。以下是此代码片段:

const axios = require("axios")

//config object

const config = {

method: 'post',

url: 'http://localhost:8080/ecommerce/postProducts',

data: {

name: 'Pixel 6A',

cost: 'Latest offering by Google. Clean UI',

categoryId: 5,

cost: 28000

}

}

// passing the config object to the Axios method and logging the response

axios(config).then(response => console.log(response.data))

以下是对此请求的响应:

为了便于使用,还有一些默认方法。例如,对于对活动建议 API 的 GET 请求,我们可以简单地使用以下代码:

const axios = require("axios")

axios('https://www.boredapi.com/api/activity').then(res => console.log(res.data))

请注意,甚至没有必要提及 get 方法。以下是控制台中的响应数据:

超越 JavaScript 基础知识:我们的全栈 Web 开发人员课程将指导您掌握高级技术。立即注册并转变您的编码专业知识。

Axios 响应对象架构

到目前为止,我们只看到了数据对象,但我们也在 Response 对象中接收了其他属性。让我们看一下整个响应对象:

若要获取完整响应,请使用以下代码片段:

const axios = require("axios")

axios('https://catfact.ninja/fact').then(res => console.log(res))

对请求的响应:

{

status: 200,

statusText: 'OK',

headers: AxiosHeaders {

server: 'nginx',

date: 'Tue, 08 Nov 2022 08:13:56 GMT',

'content-type': 'application/json',

'transfer-encoding': 'chunked',

connection: 'close',

[Symbol(defaults)]: null

},

config: {

transitional: {

silentJSONParsing: true,

forcedJSONParsing: true,

clarifyTimeoutError: false

},

adapter: [Function: httpAdapter],

transformRequest: [ [Function: transformRequest] ],

transformResponse: [ [Function: transformResponse] ],

timeout: 0,

xsrfCookieName: 'XSRF-TOKEN',

xsrfHeaderName: 'X-XSRF-TOKEN',

maxContentLength: -1,

maxBodyLength: -1,

env: { FormData: [Function], Blob: null },

validateStatus: [Function: validateStatus],

headers: AxiosHeaders {

'User-Agent': 'axios/1.1.3',

'Accept-Encoding': 'gzip, deflate, br',

[Symbol(defaults)]: [Object]

},

url: 'https://catfact.ninja/fact',

method: 'get',

data: undefined

},

data: {

fact: "Cats, just like people, are subject to asthma. Dust, smoke, and other forms of air pollution in your cat's environment can be troublesome sources of irritation.",

length: 160

}

}

下面是一个小的响应对象。我们可以看到各种属性,例如:

地位:请求的状态代码以及状态文本。头:标头包含有关请求的额外信息。配置:请求的配置数据。网址:向其发出请求的基 URL。方法:Request 方法,如 Get、Post、Patch、Delete 等。数据:数据对象是实际的 API 数据。

Axios 响应正文

如果我们只想要响应数据,那么我们对代码进行小幅修改:

const axios = require("axios")

axios('https://catfact.ninja/fact').then(res => console.log(res.data))

请求的数据:

Axios 错误处理

我们可以使用 catch 块来处理错误。Axios 为我们提供了一个 error 对象来更好地处理错误。让我们尝试请求获取没有凭据的用户的数据。以下是摘要:

const axios = require("axios")

// Make a request for user data with user id = 5

axios.get('https://api.coinbase.com/v2/users/5')

.then(function (response) {

// if successful then log the response status and data

console.log(response.status);

console.log(response.data);

})

.catch(function (error) {

// if not successful then log the error

if(error.response){

console.log(error.response.status);

console.log(error.response.statusText);

console.log(error.response.data);

}else{

console.log('The error is ', error.message);

}

})

.finally(function () {

// always executed

});

此 API 调用将引发错误,因为我们无权根据 GET 请求访问 userId = 5 的用户的数据。这是控制台中的错误:

我们已经记录了错误状态代码、错误消息和错误数据对象。这让用户知道他们正在尝试访问未经授权的资源,因此他们收到错误。

使用 Async-Await 处理 Axios 错误

由于 Axios 是基于 Promise 的,因此我们也可以使用 Async-Await。在这里,我们将尝试使用 async-await 功能处理错误。

// async function

const getUser = async () => {

try {

// using async-await to get the data from the URL

const response = await axios.get('https://api.coinbase.com/v2/users/5')

console.log(response);

} catch ( err ){

if(err.response){

console.log(err.response.status);

console.log(err.response.statusText);

console.log(err.response.data);

}

}

}

getUser()

以下是控制台中的响应:

同样,Async-Await 语法也可用于所有 CRUD - 创建、读取、更新、删除请求。我们可以在 Node.js 中使用 async-await 和 Axios 发送 GET、PUT、POST 和 DELETE 请求。

如何删除 Axios 包?

要从应用程序中卸载 Axios,只需运行以下命令:

npm 卸载 axios

这将卸载 Axios 依赖项。

结论

Axios 是一个库,用于从 Node.js 发出 HTTP 请求和从浏览器发出 XHR 请求。我们可以使用内置方法轻松调用 REST API 并执行 CRUD 操作。它会自动解析 JSON 并将 JSON 对象转换为 JavaScript 对象。Axios 具有开箱即用的错误处理功能,使调试更容易。Axios 还可用于设置请求超时以及中止或取消请求。它比本机 fetch 方法更容易使用。由于 Axios 基于 promise,因此它可以与 .then() 语法和 async-await 语法一起使用。Axios 易于与应用程序集成,并与 React 和 Angular 等流行的框架和库一起使用。

相关文章

评论可见,请评论后查看内容,谢谢!!!评论后请刷新页面。