Đối tượng phản hồi trong Axios là gì?

Thực hiện lệnh gọi API là không thể thiếu đối với hầu hết các ứng dụng và trong khi thực hiện việc này, chúng tôi sử dụng ứng dụng khách HTTP thường có sẵn dưới dạng thư viện bên ngoài. Axios là ứng dụng khách HTTP phổ biến có sẵn dưới dạng thư viện JavaScript với hơn 22 triệu lượt tải xuống hàng tuần kể từ tháng 5 năm 2022

Chúng ta có thể thực hiện lệnh gọi API với Axios từ các ứng dụng JavaScript bất kể JavaScript đang chạy trên giao diện người dùng như trình duyệt hay phía máy chủ

Trong bài viết này, chúng ta sẽ hiểu Axios và sử dụng các khả năng của nó để thực hiện các loại lệnh gọi API REST khác nhau từ các ứng dụng JavaScript

Mã ví dụ

Bài viết này được kèm theo một ví dụ mã làm việc trên GitHub

Tại sao chúng ta cần Axios

Trước tiên chúng ta hãy hiểu tại sao chúng ta cần sử dụng một thư viện như Axios. JavaScript đã cung cấp sẵn các đối tượng.


8 và

9 để tương tác với API

Trái ngược với các đối tượng tích hợp này, Axios là một thư viện mã nguồn mở mà chúng tôi cần đưa vào ứng dụng của mình để thực hiện lệnh gọi API qua HTTP. Nó tương tự như đối tượng


9 và trả về một đối tượng
const express = require['express']

// Get the default instance
const axios = require['axios']

const app = express[]

// Express route handler with URL: '/products' and a handler function
app.get['/products', [request, response] => {

  // Make the GET call by passing a config object to the instance
  axios[{
    method: 'get',
    url: '//localhost:3002/products'
  }].then[apiResponse => {
     // process the response
     const products = apiResponse.data
     response.json[products]
  }]
  
}]
1 của JavaScript nhưng cũng bao gồm nhiều tính năng mạnh mẽ

Một trong những khả năng quan trọng của Axios là bản chất đẳng cấu của nó, nghĩa là nó có thể chạy trong trình duyệt cũng như trong Node phía máy chủ. js có cùng codebase

Axios cũng là ứng dụng khách HTTP dựa trên lời hứa có thể được sử dụng trong JavaScript đơn giản cũng như trong các khung JavaScript nâng cao như React, Vue. js và Góc

Nó hỗ trợ tất cả các trình duyệt hiện đại, bao gồm hỗ trợ cho IE 8 trở lên

Trong các phần sau, chúng ta sẽ xem xét các ví dụ về việc sử dụng các tính năng này của Axios trong các ứng dụng của mình

Cài đặt Axios và các điều kiện tiên quyết khác cho các ví dụ

Chúng tôi đã tạo các ứng dụng sau để mô phỏng API trên máy chủ được sử dụng bởi các ứng dụng khác trên máy chủ và trình duyệt bằng API REST

  1. const express = require['express']
    
    // Get the default instance
    const axios = require['axios']
    
    const app = express[]
    
    // Express route handler with URL: '/products' and a handler function
    app.get['/products', [request, response] => {
    
      // Make the GET call by passing a config object to the instance
      axios[{
        method: 'get',
        url: '//localhost:3002/products'
      }].then[apiResponse => {
         // process the response
         const products = apiResponse.data
         response.json[products]
      }]
      
    }]
    
    2. Đây là một nút. js được viết bằng Express Framework sẽ chứa API REST
  2. const express = require['express']
    
    // Get the default instance
    const axios = require['axios']
    
    const app = express[]
    
    // Express route handler with URL: '/products' and a handler function
    app.get['/products', [request, response] => {
    
      // Make the GET call by passing a config object to the instance
      axios[{
        method: 'get',
        url: '//localhost:3002/products'
      }].then[apiResponse => {
         // process the response
         const products = apiResponse.data
         response.json[products]
      }]
      
    }]
    
    3. Đây cũng là một nút. js được viết bằng Express sẽ gọi các API REST được cung cấp bởi ứng dụng
    const express = require['express']
    
    // Get the default instance
    const axios = require['axios']
    
    const app = express[]
    
    // Express route handler with URL: '/products' and a handler function
    app.get['/products', [request, response] => {
    
      // Make the GET call by passing a config object to the instance
      axios[{
        method: 'get',
        url: '//localhost:3002/products'
      }].then[apiResponse => {
         // process the response
         const products = apiResponse.data
         response.json[products]
      }]
      
    }]
    
    2 bằng ứng dụng khách HTTP
    const express = require['express']
    
    // Get the default instance
    const axios = require['axios']
    
    const app = express[]
    
    // Express route handler with URL: '/products' and a handler function
    app.get['/products', [request, response] => {
    
      // Make the GET call by passing a config object to the instance
      axios[{
        method: 'get',
        url: '//localhost:3002/products'
      }].then[apiResponse => {
         // process the response
         const products = apiResponse.data
         response.json[products]
      }]
      
    }]
    
    5
  3. const express = require['express']
    
    // Get the default instance
    const axios = require['axios']
    
    const app = express[]
    
    // Express route handler with URL: '/products' and a handler function
    app.get['/products', [request, response] => {
    
      // Make the GET call by passing a config object to the instance
      axios[{
        method: 'get',
        url: '//localhost:3002/products'
      }].then[apiResponse => {
         // process the response
         const products = apiResponse.data
         response.json[products]
      }]
      
    }]
    
    6. Đây là một ứng dụng giao diện người dùng được viết bằng React, ứng dụng này cũng sẽ gọi các API REST do ứng dụng
    const express = require['express']
    
    // Get the default instance
    const axios = require['axios']
    
    const app = express[]
    
    // Express route handler with URL: '/products' and a handler function
    app.get['/products', [request, response] => {
    
      // Make the GET call by passing a config object to the instance
      axios[{
        method: 'get',
        url: '//localhost:3002/products'
      }].then[apiResponse => {
         // process the response
         const products = apiResponse.data
         response.json[products]
      }]
      
    }]
    
    2 cung cấp

Thay vì Express, chúng tôi có thể đã sử dụng bất kỳ khung JavaScript nào khác hoặc thậm chí các ứng dụng JavaScript thô. Để hiểu về Express, vui lòng tham khảo loạt bài viết về Express của chúng tôi bắt đầu với Bắt đầu trên Express

Chúng tôi sẽ cần cài đặt thư viện Axios trong hai trong số các ứng dụng này.

const express = require['express']

// Get the default instance
const axios = require['axios']

const app = express[]

// Express route handler with URL: '/products' and a handler function
app.get['/products', [request, response] => {

  // Make the GET call by passing a config object to the instance
  axios[{
    method: 'get',
    url: '//localhost:3002/products'
  }].then[apiResponse => {
     // process the response
     const products = apiResponse.data
     response.json[products]
  }]
  
}]
3 và
const express = require['express']

// Get the default instance
const axios = require['axios']

const app = express[]

// Express route handler with URL: '/products' and a handler function
app.get['/products', [request, response] => {

  // Make the GET call by passing a config object to the instance
  axios[{
    method: 'get',
    url: '//localhost:3002/products'
  }].then[apiResponse => {
     // process the response
     const products = apiResponse.data
     response.json[products]
  }]
  
}]
6 sẽ thực hiện lệnh gọi API. Hãy để chúng tôi thay đổi từng thư mục này và cài đặt Axios bằng cách sử dụng
const express = require['express']

// Get the default instance
const axios = require['axios']

const app = express[]

// Express route handler with URL: '/products/new' and a handler function
app.post['/products/new', async [request, response] => {

  const name = request.body.name
  const brand = request.body.brand

  const newProduct = {name: name, brand:brand}

  // Make the POST call by passing a config object to the instance
  axios[{
    method: 'post',
    url: '//localhost:3002/products',
    data: newProduct,
    headers: {'Authorization': 'XXXXXX'}
  }].then[apiResponse=>{
     const products = apiResponse.data
     response.json[products]
  }]
}]
0

const express = require['express']

// Get the default instance
const axios = require['axios']

const app = express[]

// Express route handler with URL: '/products/new' and a handler function
app.post['/products/new', async [request, response] => {

  const name = request.body.name
  const brand = request.body.brand

  const newProduct = {name: name, brand:brand}

  // Make the POST call by passing a config object to the instance
  axios[{
    method: 'post',
    url: '//localhost:3002/products',
    data: newProduct,
    headers: {'Authorization': 'XXXXXX'}
  }].then[apiResponse=>{
     const products = apiResponse.data
     response.json[products]
  }]
}]
1 trong Nút của chúng tôi. Ứng dụng js express sau khi cài đặt mô-đun
const express = require['express']

// Get the default instance
const axios = require['axios']

const app = express[]

// Express route handler with URL: '/products/new' and a handler function
app.post['/products/new', async [request, response] => {

  const name = request.body.name
  const brand = request.body.brand

  const newProduct = {name: name, brand:brand}

  // Make the POST call by passing a config object to the instance
  axios[{
    method: 'post',
    url: '//localhost:3002/products',
    data: newProduct,
    headers: {'Authorization': 'XXXXXX'}
  }].then[apiResponse=>{
     const products = apiResponse.data
     response.json[products]
  }]
}]
2 trông như thế này

{
  "name": "serversideapp",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  ...
  ...
  "dependencies": {
    "axios": "^0.27.2",
    "cors": "^2.8.5",
    "express": "^4.18.1"
  }
}

Chúng ta có thể thấy mô-đun

const express = require['express']

// Get the default instance
const axios = require['axios']

const app = express[]

// Express route handler with URL: '/products/new' and a handler function
app.post['/products/new', async [request, response] => {

  const name = request.body.name
  const brand = request.body.brand

  const newProduct = {name: name, brand:brand}

  // Make the POST call by passing a config object to the instance
  axios[{
    method: 'post',
    url: '//localhost:3002/products',
    data: newProduct,
    headers: {'Authorization': 'XXXXXX'}
  }].then[apiResponse=>{
     const products = apiResponse.data
     response.json[products]
  }]
}]
2 được thêm vào dưới dạng phụ thuộc trong phần tử
const express = require['express']

// Get the default instance
const axios = require['axios']

const app = express[]

// Express route handler with URL: '/products/new' and a handler function
app.post['/products/new', async [request, response] => {

  const name = request.body.name
  const brand = request.body.brand

  const newProduct = {name: name, brand:brand}

  // Make the POST call by passing a config object to the instance
  axios[{
    method: 'post',
    url: '//localhost:3002/products',
    data: newProduct,
    headers: {'Authorization': 'XXXXXX'}
  }].then[apiResponse=>{
     const products = apiResponse.data
     response.json[products]
  }]
}]
4

Nếu chúng ta muốn gọi các API bằng Axios từ một ứng dụng JavaScript vanilla, thì chúng ta cần đưa nó vào từ một Mạng phân phối nội dung [CDN] như được hiển thị ở đây


Sau khi thiết lập các ứng dụng của chúng ta, bây giờ chúng ta bắt đầu gọi các API được cung cấp bởi

const express = require['express']

// Get the default instance
const axios = require['axios']

const app = express[]

// Express route handler with URL: '/products' and a handler function
app.get['/products', [request, response] => {

  // Make the GET call by passing a config object to the instance
  axios[{
    method: 'get',
    url: '//localhost:3002/products'
  }].then[apiResponse => {
     // process the response
     const products = apiResponse.data
     response.json[products]
  }]
  
}]
2 từ
const express = require['express']

// Get the default instance
const axios = require['axios']

const app = express[]

// Express route handler with URL: '/products/new' and a handler function
app.post['/products/new', async [request, response] => {

  const name = request.body.name
  const brand = request.body.brand

  const newProduct = {name: name, brand:brand}

  // Make the POST call by passing a config object to the instance
  axios[{
    method: 'post',
    url: '//localhost:3002/products',
    data: newProduct,
    headers: {'Authorization': 'XXXXXX'}
  }].then[apiResponse=>{
     const products = apiResponse.data
     response.json[products]
  }]
}]
6 và
const express = require['express']

// Get the default instance
const axios = require['axios']

const app = express[]

// Express route handler with URL: '/products' and a handler function
app.get['/products', [request, response] => {

  // Make the GET call by passing a config object to the instance
  axios[{
    method: 'get',
    url: '//localhost:3002/products'
  }].then[apiResponse => {
     // process the response
     const products = apiResponse.data
     response.json[products]
  }]
  
}]
6 bằng ứng dụng khách HTTP Axios trong các phần sau

Gửi yêu cầu với Phiên bản Axios

Chúng ta hãy bắt đầu bằng cách gọi phương thức

const express = require['express']

// Get the default instance
const axios = require['axios']

const app = express[]

// Express route handler with URL: '/products/new' and a handler function
app.post['/products/new', async [request, response] => {

  const name = request.body.name
  const brand = request.body.brand

  const newProduct = {name: name, brand:brand}

  // Make the POST call by passing a config object to the instance
  axios[{
    method: 'post',
    url: '//localhost:3002/products',
    data: newProduct,
    headers: {'Authorization': 'XXXXXX'}
  }].then[apiResponse=>{
     const products = apiResponse.data
     response.json[products]
  }]
}]
8 với ứng dụng khách Axios HTTP từ ứng dụng phía máy chủ của chúng ta.
const express = require['express']

// Get the default instance
const axios = require['axios']

const app = express[]

// Express route handler with URL: '/products/new' and a handler function
app.post['/products/new', async [request, response] => {

  const name = request.body.name
  const brand = request.body.brand

  const newProduct = {name: name, brand:brand}

  // Make the POST call by passing a config object to the instance
  axios[{
    method: 'post',
    url: '//localhost:3002/products',
    data: newProduct,
    headers: {'Authorization': 'XXXXXX'}
  }].then[apiResponse=>{
     const products = apiResponse.data
     response.json[products]
  }]
}]
6

Để thực hiện việc này, chúng tôi sẽ thêm chức năng xử lý tuyến Express với một URL.

const express = require['express']

// Get the default instance
const axios = require['axios']

const app = express[]

// Express route handler for making a request for fetching a product
app.get['/products/:productName', [request, response] => {

  const productName = request.params.productName  

  axios.get[`//localhost:3002/products/${productName}`]
  .then[apiResponse => {
     const product = apiResponse.data
     response.json[product]
  }]   
}]
0 vào ứng dụng. Trong chức năng xử lý tuyến đường, chúng tôi sẽ tìm nạp danh sách các sản phẩm bằng cách gọi một API từ
const express = require['express']

// Get the default instance
const axios = require['axios']

const app = express[]

// Express route handler with URL: '/products' and a handler function
app.get['/products', [request, response] => {

  // Make the GET call by passing a config object to the instance
  axios[{
    method: 'get',
    url: '//localhost:3002/products'
  }].then[apiResponse => {
     // process the response
     const products = apiResponse.data
     response.json[products]
  }]
  
}]
2 của chúng tôi với URL.
const express = require['express']

// Get the default instance
const axios = require['axios']

const app = express[]

// Express route handler for making a request for fetching a product
app.get['/products/:productName', [request, response] => {

  const productName = request.params.productName  

  axios.get[`//localhost:3002/products/${productName}`]
  .then[apiResponse => {
     const product = apiResponse.data
     response.json[product]
  }]   
}]
2

Chúng tôi sẽ sử dụng chữ ký.

const express = require['express']

// Get the default instance
const axios = require['axios']

const app = express[]

// Express route handler for making a request for fetching a product
app.get['/products/:productName', [request, response] => {

  const productName = request.params.productName  

  axios.get[`//localhost:3002/products/${productName}`]
  .then[apiResponse => {
     const product = apiResponse.data
     response.json[product]
  }]   
}]
3 trên phiên bản mặc định do ứng dụng khách Axios HTTP cung cấp để thực hiện việc này

const express = require['express']

// Get the default instance
const axios = require['axios']

const app = express[]

// Express route handler with URL: '/products' and a handler function
app.get['/products', [request, response] => {

  // Make the GET call by passing a config object to the instance
  axios[{
    method: 'get',
    url: '//localhost:3002/products'
  }].then[apiResponse => {
     // process the response
     const products = apiResponse.data
     response.json[products]
  }]
  
}]

Trong ví dụ này, trước tiên chúng ta gọi

const express = require['express']

// Get the default instance
const axios = require['axios']

const app = express[]

// Express route handler for making a request for fetching a product
app.get['/products/:productName', [request, response] => {

  const productName = request.params.productName  

  axios.get[`//localhost:3002/products/${productName}`]
  .then[apiResponse => {
     const product = apiResponse.data
     response.json[product]
  }]   
}]
4 để nhận một phiên bản.
const express = require['express']

// Get the default instance
const axios = require['axios']

const app = express[]

// Express route handler with URL: '/products/new' and a handler function
app.post['/products/new', async [request, response] => {

  const name = request.body.name
  const brand = request.body.brand

  const newProduct = {name: name, brand:brand}

  // Make the POST call by passing a config object to the instance
  axios[{
    method: 'post',
    url: '//localhost:3002/products',
    data: newProduct,
    headers: {'Authorization': 'XXXXXX'}
  }].then[apiResponse=>{
     const products = apiResponse.data
     response.json[products]
  }]
}]
2 được thiết lập với cấu hình mặc định

Sau đó, chúng tôi sẽ chuyển một đối số cấu hình cho đối tượng

const express = require['express']

// Get the default instance
const axios = require['axios']

const app = express[]

// Express route handler with URL: '/products/new' and a handler function
app.post['/products/new', async [request, response] => {

  const name = request.body.name
  const brand = request.body.brand

  const newProduct = {name: name, brand:brand}

  // Make the POST call by passing a config object to the instance
  axios[{
    method: 'post',
    url: '//localhost:3002/products',
    data: newProduct,
    headers: {'Authorization': 'XXXXXX'}
  }].then[apiResponse=>{
     const products = apiResponse.data
     response.json[products]
  }]
}]
2 có chứa tham số
const express = require['express']

// Get the default instance
const axios = require['axios']

const app = express[]

// Express route handler for making a request for fetching a product
app.get['/products/:productName', [request, response] => {

  const productName = request.params.productName  

  axios.get[`//localhost:3002/products/${productName}`]
  .then[apiResponse => {
     const product = apiResponse.data
     response.json[product]
  }]   
}]
7 được đặt thành phương thức HTTP.
const express = require['express']

// Get the default instance
const axios = require['axios']

const app = express[]

// Express route handler for making a request for fetching a product
app.get['/products/:productName', [request, response] => {

  const productName = request.params.productName  

  axios.get[`//localhost:3002/products/${productName}`]
  .then[apiResponse => {
     const product = apiResponse.data
     response.json[product]
  }]   
}]
8 và tham số
const express = require['express']

// Get the default instance
const axios = require['axios']

const app = express[]

// Express route handler for making a request for fetching a product
app.get['/products/:productName', [request, response] => {

  const productName = request.params.productName  

  axios.get[`//localhost:3002/products/${productName}`]
  .then[apiResponse => {
     const product = apiResponse.data
     response.json[product]
  }]   
}]
9 được đặt thành URL của điểm cuối REST.
const express = require['express']

// Get the default instance
const axios = require['axios']

const app = express[]

// Express route handler for making a request for fetching a product
app.get['/products/:productName', [request, response] => {

  const productName = request.params.productName  

  axios.get[`//localhost:3002/products/${productName}`]
  .then[apiResponse => {
     const product = apiResponse.data
     response.json[product]
  }]   
}]
2. Tham số
const express = require['express']

// Get the default instance
const axios = require['axios']

const app = express[]

// Express route handler for making a request for fetching a product
app.get['/products/:productName', [request, response] => {

  const productName = request.params.productName  

  axios.get[`//localhost:3002/products/${productName}`]
  .then[apiResponse => {
     const product = apiResponse.data
     response.json[product]
  }]   
}]
9 là bắt buộc trong khi chúng ta có thể bỏ qua tham số
const express = require['express']

// Get the default instance
const axios = require['axios']

const app = express[]

// Express route handler for making a request for fetching a product
app.get['/products/:productName', [request, response] => {

  const productName = request.params.productName  

  axios.get[`//localhost:3002/products/${productName}`]
  .then[apiResponse => {
     const product = apiResponse.data
     response.json[product]
  }]   
}]
7 sau đó sẽ mặc định là
const express = require['express']

// Get the default instance
const axios = require['axios']

const app = express[]

// Express route handler for making a request for fetching a product
app.get['/products/:productName', [request, response] => {

  const productName = request.params.productName  

  axios.get[`//localhost:3002/products/${productName}`]
  .then[apiResponse => {
     const product = apiResponse.data
     response.json[product]
  }]   
}]
8

Phương thức này trả về một đối tượng JavaScript

const express = require['express']

// Get the default instance
const axios = require['axios']

const app = express[]

// Express route handler with URL: '/products' and a handler function
app.get['/products', [request, response] => {

  // Make the GET call by passing a config object to the instance
  axios[{
    method: 'get',
    url: '//localhost:3002/products'
  }].then[apiResponse => {
     // process the response
     const products = apiResponse.data
     response.json[products]
  }]
  
}]
1, nghĩa là chương trình không đợi phương thức hoàn thành trước khi thử thực hiện câu lệnh tiếp theo.
const express = require['express']

// Get the default instance
const axios = require['axios']

const app = express[]

// Express route handler with URL: '/products' and a handler function
app.get['/products', [request, response] => {

  // Make the GET call by passing a config object to the instance
  axios[{
    method: 'get',
    url: '//localhost:3002/products'
  }].then[apiResponse => {
     // process the response
     const products = apiResponse.data
     response.json[products]
  }]
  
}]
1 được thực hiện hoặc bị từ chối, tùy thuộc vào phản hồi từ API

Chúng tôi sử dụng phương pháp

const axios = require['axios']
axios.get[`//localhost:3002/products/`, {
    params: {
      productName: productName
    }
  }]
  .then[apiResponse => {
     const product = apiResponse.data
     response.json[product]
  }]   
6 như trong ví dụ này để xử lý kết quả. Phương thức
const axios = require['axios']
axios.get[`//localhost:3002/products/`, {
    params: {
      productName: productName
    }
  }]
  .then[apiResponse => {
     const product = apiResponse.data
     response.json[product]
  }]   
6 được thực thi khi hoàn thành
const express = require['express']

// Get the default instance
const axios = require['axios']

const app = express[]

// Express route handler with URL: '/products' and a handler function
app.get['/products', [request, response] => {

  // Make the GET call by passing a config object to the instance
  axios[{
    method: 'get',
    url: '//localhost:3002/products'
  }].then[apiResponse => {
     // process the response
     const products = apiResponse.data
     response.json[products]
  }]
  
}]
1. Trong ví dụ của chúng tôi, trong phương thức
const axios = require['axios']
axios.get[`//localhost:3002/products/`, {
    params: {
      productName: productName
    }
  }]
  .then[apiResponse => {
     const product = apiResponse.data
     response.json[product]
  }]   
9, chúng tôi trích xuất danh sách của
const express = require['express']
const axios = require['axios']

const app = express[]

app.get['/products/async/:productName', async [request, response] => {
  const productName = request.params.productName  

  const apiResponse = await axios.get[`//localhost:3002/products/`, {
    params: {
      productName: productName
    }
  }]

  const product = apiResponse.data
  response.json[product]
}]
0 bằng cách gọi
const express = require['express']
const axios = require['axios']

const app = express[]

app.get['/products/async/:productName', async [request, response] => {
  const productName = request.params.productName  

  const apiResponse = await axios.get[`//localhost:3002/products/`, {
    params: {
      productName: productName
    }
  }]

  const product = apiResponse.data
  response.json[product]
}]
1

Tương tự, một yêu cầu

const express = require['express']
const axios = require['axios']

const app = express[]

app.get['/products/async/:productName', async [request, response] => {
  const productName = request.params.productName  

  const apiResponse = await axios.get[`//localhost:3002/products/`, {
    params: {
      productName: productName
    }
  }]

  const product = apiResponse.data
  response.json[product]
}]
2 để thêm một
const express = require['express']
const axios = require['axios']

const app = express[]

app.get['/products/async/:productName', async [request, response] => {
  const productName = request.params.productName  

  const apiResponse = await axios.get[`//localhost:3002/products/`, {
    params: {
      productName: productName
    }
  }]

  const product = apiResponse.data
  response.json[product]
}]
3 mới được thực hiện với phiên bản mặc định của
const express = require['express']

// Get the default instance
const axios = require['axios']

const app = express[]

// Express route handler with URL: '/products/new' and a handler function
app.post['/products/new', async [request, response] => {

  const name = request.body.name
  const brand = request.body.brand

  const newProduct = {name: name, brand:brand}

  // Make the POST call by passing a config object to the instance
  axios[{
    method: 'post',
    url: '//localhost:3002/products',
    data: newProduct,
    headers: {'Authorization': 'XXXXXX'}
  }].then[apiResponse=>{
     const products = apiResponse.data
     response.json[products]
  }]
}]
2 sẽ giống như thế này

const express = require['express']

// Get the default instance
const axios = require['axios']

const app = express[]

// Express route handler with URL: '/products/new' and a handler function
app.post['/products/new', async [request, response] => {

  const name = request.body.name
  const brand = request.body.brand

  const newProduct = {name: name, brand:brand}

  // Make the POST call by passing a config object to the instance
  axios[{
    method: 'post',
    url: '//localhost:3002/products',
    data: newProduct,
    headers: {'Authorization': 'XXXXXX'}
  }].then[apiResponse=>{
     const products = apiResponse.data
     response.json[products]
  }]
}]

Trong ví dụ này, ngoài những gì chúng ta đã làm để gọi phương thức

const express = require['express']

// Get the default instance
const axios = require['axios']

const app = express[]

// Express route handler with URL: '/products/new' and a handler function
app.post['/products/new', async [request, response] => {

  const name = request.body.name
  const brand = request.body.brand

  const newProduct = {name: name, brand:brand}

  // Make the POST call by passing a config object to the instance
  axios[{
    method: 'post',
    url: '//localhost:3002/products',
    data: newProduct,
    headers: {'Authorization': 'XXXXXX'}
  }].then[apiResponse=>{
     const products = apiResponse.data
     response.json[products]
  }]
}]
8, chúng ta đã thiết lập phần tử
const express = require['express']
const axios = require['axios']

const app = express[]

app.get['/products/async/:productName', async [request, response] => {
  const productName = request.params.productName  

  const apiResponse = await axios.get[`//localhost:3002/products/`, {
    params: {
      productName: productName
    }
  }]

  const product = apiResponse.data
  response.json[product]
}]
6 chứa biểu diễn JSON của
const express = require['express']
const axios = require['axios']

const app = express[]

app.get['/products/async/:productName', async [request, response] => {
  const productName = request.params.productName  

  const apiResponse = await axios.get[`//localhost:3002/products/`, {
    params: {
      productName: productName
    }
  }]

  const product = apiResponse.data
  response.json[product]
}]
7 mới cùng với tiêu đề
const express = require['express']
const axios = require['axios']

const app = express[]

app.get['/products/async/:productName', async [request, response] => {
  const productName = request.params.productName  

  const apiResponse = await axios.get[`//localhost:3002/products/`, {
    params: {
      productName: productName
    }
  }]

  const product = apiResponse.data
  response.json[product]
}]
8. Chúng tôi đang xử lý phản hồi trong hàm
const axios = require['axios']
axios.get[`//localhost:3002/products/`, {
    params: {
      productName: productName
    }
  }]
  .then[apiResponse => {
     const product = apiResponse.data
     response.json[product]
  }]   
9 trên phản hồi
const express = require['express']

// Get the default instance
const axios = require['axios']

const app = express[]

// Express route handler with URL: '/products' and a handler function
app.get['/products', [request, response] => {

  // Make the GET call by passing a config object to the instance
  axios[{
    method: 'get',
    url: '//localhost:3002/products'
  }].then[apiResponse => {
     // process the response
     const products = apiResponse.data
     response.json[products]
  }]
  
}]
1 nơi chúng tôi đang trích xuất dữ liệu phản hồi API bằng cách gọi
const express = require['express']
const axios = require['axios']

const app = express[]

app.get['/products/async/:productName', async [request, response] => {
  const productName = request.params.productName  

  const apiResponse = await axios.get[`//localhost:3002/products/`, {
    params: {
      productName: productName
    }
  }]

  const product = apiResponse.data
  response.json[product]
}]
1

Để xử lý phản hồi API liên quan nhiều hơn, bạn nên hiểu tất cả các yếu tố của phản hồi được trả về bởi lệnh gọi API được thực hiện với

const express = require['express']

// Get the default instance
const axios = require['axios']

const app = express[]

// Express route handler with URL: '/products/new' and a handler function
app.post['/products/new', async [request, response] => {

  const name = request.body.name
  const brand = request.body.brand

  const newProduct = {name: name, brand:brand}

  // Make the POST call by passing a config object to the instance
  axios[{
    method: 'post',
    url: '//localhost:3002/products',
    data: newProduct,
    headers: {'Authorization': 'XXXXXX'}
  }].then[apiResponse=>{
     const products = apiResponse.data
     response.json[products]
  }]
}]
2

  • dữ liệu. Tải trọng phản hồi được gửi bởi máy chủ
  • tình trạng. Mã trạng thái HTTP từ phản hồi của máy chủ
  • statusText. Thông báo trạng thái HTTP từ phản hồi của máy chủ
  • tiêu đề. Tiêu đề HTTP nhận được trong phản hồi API
  • cấu hình. config được gửi đến phiên bản
    const express = require['express']
    
    // Get the default instance
    const axios = require['axios']
    
    const app = express[]
    
    // Express route handler with URL: '/products/new' and a handler function
    app.post['/products/new', async [request, response] => {
    
      const name = request.body.name
      const brand = request.body.brand
    
      const newProduct = {name: name, brand:brand}
    
      // Make the POST call by passing a config object to the instance
      axios[{
        method: 'post',
        url: '//localhost:3002/products',
        data: newProduct,
        headers: {'Authorization': 'XXXXXX'}
      }].then[apiResponse=>{
         const products = apiResponse.data
         response.json[products]
      }]
    }]
    
    2 để gửi yêu cầu
  • lời yêu cầu. Yêu cầu tạo ra phản hồi này. Đây là phiên bản ClientRequest cuối cùng trong nút. js [trong chuyển hướng] và một phiên bản XMLHttpRequest trong trình duyệt

Gửi yêu cầu bằng các phương thức sơ thẩm tiện lợi của Axios

Axios cũng cung cấp một chữ ký thay thế để thực hiện lệnh gọi API bằng cách cung cấp các phương thức tiện lợi cho tất cả các phương thức HTTP như.

const express = require['express']
const axios = require['axios']

const app = express[]

app.post['/products', async [request, response] => {

    const name = request.body.name
    const brand = request.body.brand

    const newProduct = {name: name, brand:brand}

    const apiResponse = await axios.post[`//localhost:3002/products/`, newProduct]

    const product = apiResponse.data
    response.json[{result:"OK"}]
}]
4,
const express = require['express']
const axios = require['axios']

const app = express[]

app.post['/products', async [request, response] => {

    const name = request.body.name
    const brand = request.body.brand

    const newProduct = {name: name, brand:brand}

    const apiResponse = await axios.post[`//localhost:3002/products/`, newProduct]

    const product = apiResponse.data
    response.json[{result:"OK"}]
}]
5,
const express = require['express']
const axios = require['axios']

const app = express[]

app.post['/products', async [request, response] => {

    const name = request.body.name
    const brand = request.body.brand

    const newProduct = {name: name, brand:brand}

    const apiResponse = await axios.post[`//localhost:3002/products/`, newProduct]

    const product = apiResponse.data
    response.json[{result:"OK"}]
}]
6,
const express = require['express']
const axios = require['axios']

const app = express[]

app.post['/products', async [request, response] => {

    const name = request.body.name
    const brand = request.body.brand

    const newProduct = {name: name, brand:brand}

    const apiResponse = await axios.post[`//localhost:3002/products/`, newProduct]

    const product = apiResponse.data
    response.json[{result:"OK"}]
}]
7, v.v.

Chúng ta có thể viết ví dụ trước để gọi phương thức

const express = require['express']

// Get the default instance
const axios = require['axios']

const app = express[]

// Express route handler with URL: '/products/new' and a handler function
app.post['/products/new', async [request, response] => {

  const name = request.body.name
  const brand = request.body.brand

  const newProduct = {name: name, brand:brand}

  // Make the POST call by passing a config object to the instance
  axios[{
    method: 'post',
    url: '//localhost:3002/products',
    data: newProduct,
    headers: {'Authorization': 'XXXXXX'}
  }].then[apiResponse=>{
     const products = apiResponse.data
     response.json[products]
  }]
}]
8 của API REST bằng phương thức tiện lợi.
const express = require['express']
const axios = require['axios']

const app = express[]

app.post['/products', async [request, response] => {

    const name = request.body.name
    const brand = request.body.brand

    const newProduct = {name: name, brand:brand}

    const apiResponse = await axios.post[`//localhost:3002/products/`, newProduct]

    const product = apiResponse.data
    response.json[{result:"OK"}]
}]
4 như hình bên dưới

const express = require['express']

// Get the default instance
const axios = require['axios']

const app = express[]

// Express route handler for making a request for fetching a product
app.get['/products/:productName', [request, response] => {

  const productName = request.params.productName  

  axios.get[`//localhost:3002/products/${productName}`]
  .then[apiResponse => {
     const product = apiResponse.data
     response.json[product]
  }]   
}]

Trong ví dụ này, trong hàm Express route handler, chúng tôi đang gọi phương thức

import React, { useState } from 'react'
import axios from 'axios'

export default function ProductList[]{
    const [products, setProducts] =  useState[[]]

    const fetchProducts = []=>{
       axios.get[`//localhost:3001/products`]
      .then[response => {
        const products = response.data
        setProducts[products]
      }]      
     
    }

    return [
        
          

Product List

Fetch Products

    { products .map[product =>
  • {product.name} {product.brand}
  • ] }
] }
0 trên phiên bản mặc định của
const express = require['express']

// Get the default instance
const axios = require['axios']

const app = express[]

// Express route handler with URL: '/products/new' and a handler function
app.post['/products/new', async [request, response] => {

  const name = request.body.name
  const brand = request.body.brand

  const newProduct = {name: name, brand:brand}

  // Make the POST call by passing a config object to the instance
  axios[{
    method: 'post',
    url: '//localhost:3002/products',
    data: newProduct,
    headers: {'Authorization': 'XXXXXX'}
  }].then[apiResponse=>{
     const products = apiResponse.data
     response.json[products]
  }]
}]
2 và chuyển URL của điểm cuối API REST làm đối số duy nhất. Mã này trông ngắn gọn hơn nhiều so với chữ ký.
const express = require['express']

// Get the default instance
const axios = require['axios']

const app = express[]

// Express route handler for making a request for fetching a product
app.get['/products/:productName', [request, response] => {

  const productName = request.params.productName  

  axios.get[`//localhost:3002/products/${productName}`]
  .then[apiResponse => {
     const product = apiResponse.data
     response.json[product]
  }]   
}]
3 được sử dụng trong ví dụ ở phần trước

Chữ ký.

const express = require['express']
const axios = require['axios']

const app = express[]

app.post['/products', async [request, response] => {

    const name = request.body.name
    const brand = request.body.brand

    const newProduct = {name: name, brand:brand}

    const apiResponse = await axios.post[`//localhost:3002/products/`, newProduct]

    const product = apiResponse.data
    response.json[{result:"OK"}]
}]
4 luôn thích hợp hơn để gọi các API REST do cú pháp sạch hơn của nó. Tuy nhiên, chữ ký.
const express = require['express']

// Get the default instance
const axios = require['axios']

const app = express[]

// Express route handler for making a request for fetching a product
app.get['/products/:productName', [request, response] => {

  const productName = request.params.productName  

  axios.get[`//localhost:3002/products/${productName}`]
  .then[apiResponse => {
     const product = apiResponse.data
     response.json[product]
  }]   
}]
3 của việc chuyển một đối tượng cấu hình chứa phương thức HTTP và các tham số URL tới đối tượng
const express = require['express']

// Get the default instance
const axios = require['axios']

const app = express[]

// Express route handler with URL: '/products/new' and a handler function
app.post['/products/new', async [request, response] => {

  const name = request.body.name
  const brand = request.body.brand

  const newProduct = {name: name, brand:brand}

  // Make the POST call by passing a config object to the instance
  axios[{
    method: 'post',
    url: '//localhost:3002/products',
    data: newProduct,
    headers: {'Authorization': 'XXXXXX'}
  }].then[apiResponse=>{
     const products = apiResponse.data
     response.json[products]
  }]
}]
2 có thể được sử dụng trong các tình huống mà chúng tôi muốn xây dựng các lệnh gọi API một cách linh hoạt

Phương thức

import React, { useState } from 'react'
import axios from 'axios'

export default function ProductList[]{
    const [products, setProducts] =  useState[[]]

    const fetchProducts = []=>{
       axios.get[`//localhost:3001/products`]
      .then[response => {
        const products = response.data
        setProducts[products]
      }]      
     
    }

    return [
        
          

Product List

Fetch Products

    { products .map[product =>
  • {product.name} {product.brand}
  • ] }
] }
0 trả về một đối tượng JavaScript
const express = require['express']

// Get the default instance
const axios = require['axios']

const app = express[]

// Express route handler with URL: '/products' and a handler function
app.get['/products', [request, response] => {

  // Make the GET call by passing a config object to the instance
  axios[{
    method: 'get',
    url: '//localhost:3002/products'
  }].then[apiResponse => {
     // process the response
     const products = apiResponse.data
     response.json[products]
  }]
  
}]
1 tương tự như các ví dụ trước của chúng tôi, trong đó chúng tôi trích xuất danh sách
const express = require['express']
const axios = require['axios']

const app = express[]

app.get['/products/async/:productName', async [request, response] => {
  const productName = request.params.productName  

  const apiResponse = await axios.get[`//localhost:3002/products/`, {
    params: {
      productName: productName
    }
  }]

  const product = apiResponse.data
  response.json[product]
}]
0 bên trong hàm
const axios = require['axios']
axios.get[`//localhost:3002/products/`, {
    params: {
      productName: productName
    }
  }]
  .then[apiResponse => {
     const product = apiResponse.data
     response.json[product]
  }]   
9

Thay vì thêm tham số truy vấn yêu cầu vào URL trong ví dụ trước, chúng ta có thể đã chuyển tham số yêu cầu trong một đối số phương thức riêng biệt.

const express = require['express']

// get the default axios instance
const axios = require['axios']

const app = express[]

// Route Handler
app.get['/products/:productName/inventory', [request, response] => {

  const productName = request.params.productName

  // Call the first API for product details
  const productApiResponse = axios
            .get[`//localhost:3002/products/${productName}`]

  // Call the second API for inventory details
  const inventoryApiResponse = axios
            .get[`//localhost:3002/products/${productName}/itemsInStock`]

  // Consolidate results into a single result
  Promise.all[[productApiResponse, inventoryApiResponse]]
  .then[results=>{
      const productData = results[0].data
      const inventoryData = results[1].data
      let aggregateData = productData
      aggregateData.unitsInStock = inventoryData.unitsInStock
      response.send[aggregateData]
    
  }]
}]

0 như hình bên dưới

const axios = require['axios']
axios.get[`//localhost:3002/products/`, {
    params: {
      productName: productName
    }
  }]
  .then[apiResponse => {
     const product = apiResponse.data
     response.json[product]
  }]   

Chúng ta cũng có thể sử dụng cú pháp

const express = require['express']

// get the default axios instance
const axios = require['axios']

const app = express[]

// Route Handler
app.get['/products/:productName/inventory', [request, response] => {

  const productName = request.params.productName

  // Call the first API for product details
  const productApiResponse = axios
            .get[`//localhost:3002/products/${productName}`]

  // Call the second API for inventory details
  const inventoryApiResponse = axios
            .get[`//localhost:3002/products/${productName}/itemsInStock`]

  // Consolidate results into a single result
  Promise.all[[productApiResponse, inventoryApiResponse]]
  .then[results=>{
      const productData = results[0].data
      const inventoryData = results[1].data
      let aggregateData = productData
      aggregateData.unitsInStock = inventoryData.unitsInStock
      response.send[aggregateData]
    
  }]
}]

1 để gọi phương thức
import React, { useState } from 'react'
import axios from 'axios'

export default function ProductList[]{
    const [products, setProducts] =  useState[[]]

    const fetchProducts = []=>{
       axios.get[`//localhost:3001/products`]
      .then[response => {
        const products = response.data
        setProducts[products]
      }]      
     
    }

    return [
        
          

Product List

Fetch Products

    { products .map[product =>
  • {product.name} {product.brand}
  • ] }
] }
0

const express = require['express']
const axios = require['axios']

const app = express[]

app.get['/products/async/:productName', async [request, response] => {
  const productName = request.params.productName  

  const apiResponse = await axios.get[`//localhost:3002/products/`, {
    params: {
      productName: productName
    }
  }]

  const product = apiResponse.data
  response.json[product]
}]

const express = require['express']

// get the default axios instance
const axios = require['axios']

const app = express[]

// Route Handler
app.get['/products/:productName/inventory', [request, response] => {

  const productName = request.params.productName

  // Call the first API for product details
  const productApiResponse = axios
            .get[`//localhost:3002/products/${productName}`]

  // Call the second API for inventory details
  const inventoryApiResponse = axios
            .get[`//localhost:3002/products/${productName}/itemsInStock`]

  // Consolidate results into a single result
  Promise.all[[productApiResponse, inventoryApiResponse]]
  .then[results=>{
      const productData = results[0].data
      const inventoryData = results[1].data
      let aggregateData = productData
      aggregateData.unitsInStock = inventoryData.unitsInStock
      response.send[aggregateData]
    
  }]
}]

1 là một phần của ECMAScript 2017 và không được hỗ trợ trong các trình duyệt cũ hơn như IE

Tiếp theo, chúng ta hãy thực hiện một yêu cầu

const express = require['express']
const axios = require['axios']

const app = express[]

app.get['/products/async/:productName', async [request, response] => {
  const productName = request.params.productName  

  const apiResponse = await axios.get[`//localhost:3002/products/`, {
    params: {
      productName: productName
    }
  }]

  const product = apiResponse.data
  response.json[product]
}]
2 tới một API bằng phương thức thuận tiện
const express = require['express']
const axios = require['axios']

const app = express[]

app.post['/products', async [request, response] => {

    const name = request.body.name
    const brand = request.body.brand

    const newProduct = {name: name, brand:brand}

    const apiResponse = await axios.post[`//localhost:3002/products/`, newProduct]

    const product = apiResponse.data
    response.json[{result:"OK"}]
}]
5

const express = require['express']
const axios = require['axios']

const app = express[]

app.post['/products', async [request, response] => {

    const name = request.body.name
    const brand = request.body.brand

    const newProduct = {name: name, brand:brand}

    const apiResponse = await axios.post[`//localhost:3002/products/`, newProduct]

    const product = apiResponse.data
    response.json[{result:"OK"}]
}]

Ở đây chúng tôi đang sử dụng cú pháp

const express = require['express']

// get the default axios instance
const axios = require['axios']

const app = express[]

// Route Handler
app.get['/products/:productName/inventory', [request, response] => {

  const productName = request.params.productName

  // Call the first API for product details
  const productApiResponse = axios
            .get[`//localhost:3002/products/${productName}`]

  // Call the second API for inventory details
  const inventoryApiResponse = axios
            .get[`//localhost:3002/products/${productName}/itemsInStock`]

  // Consolidate results into a single result
  Promise.all[[productApiResponse, inventoryApiResponse]]
  .then[results=>{
      const productData = results[0].data
      const inventoryData = results[1].data
      let aggregateData = productData
      aggregateData.unitsInStock = inventoryData.unitsInStock
      response.send[aggregateData]
    
  }]
}]

1 để thực hiện một yêu cầu
const express = require['express']
const axios = require['axios']

const app = express[]

app.get['/products/async/:productName', async [request, response] => {
  const productName = request.params.productName  

  const apiResponse = await axios.get[`//localhost:3002/products/`, {
    params: {
      productName: productName
    }
  }]

  const product = apiResponse.data
  response.json[product]
}]
2 với phương thức
const express = require['express']
const axios = require['axios']

const app = express[]

app.post['/products', async [request, response] => {

    const name = request.body.name
    const brand = request.body.brand

    const newProduct = {name: name, brand:brand}

    const apiResponse = await axios.post[`//localhost:3002/products/`, newProduct]

    const product = apiResponse.data
    response.json[{result:"OK"}]
}]
5. Chúng tôi đang chuyển
const express = require['express']
const axios = require['axios']

const app = express[]

app.get['/products/async/:productName', async [request, response] => {
  const productName = request.params.productName  

  const apiResponse = await axios.get[`//localhost:3002/products/`, {
    params: {
      productName: productName
    }
  }]

  const product = apiResponse.data
  response.json[product]
}]
3 mới được tạo dưới dạng JSON làm tham số thứ hai của phương thức

00

Chúng ta hãy xem một ví dụ về việc sử dụng Axios trong ứng dụng giao diện người dùng được xây dựng bằng thư viện React. Đoạn mã dưới đây là từ một thành phần React gọi API để tìm nạp sản phẩm

import React, { useState } from 'react'
import axios from 'axios'

export default function ProductList[]{
    const [products, setProducts] =  useState[[]]

    const fetchProducts = []=>{
       axios.get[`//localhost:3001/products`]
      .then[response => {
        const products = response.data
        setProducts[products]
      }]      
     
    }

    return [
        
          

Product List

Fetch Products

    { products .map[product =>
  • {product.name} {product.brand}
  • ] }
] }

Như chúng ta có thể thấy, mã để thực hiện lệnh gọi API với Axios giống như mã chúng ta đã sử dụng trong Node. ứng dụng js trong các phần trước

Gửi nhiều yêu cầu đồng thời với Axios

Trong nhiều trường hợp, chúng ta cần kết hợp kết quả từ nhiều API để có kết quả tổng hợp. Với ứng dụng khách Axios HTTP, chúng ta có thể thực hiện các yêu cầu đồng thời tới nhiều API như trong ví dụ này

const express = require['express']

// get the default axios instance
const axios = require['axios']

const app = express[]

// Route Handler
app.get['/products/:productName/inventory', [request, response] => {

  const productName = request.params.productName

  // Call the first API for product details
  const productApiResponse = axios
            .get[`//localhost:3002/products/${productName}`]

  // Call the second API for inventory details
  const inventoryApiResponse = axios
            .get[`//localhost:3002/products/${productName}/itemsInStock`]

  // Consolidate results into a single result
  Promise.all[[productApiResponse, inventoryApiResponse]]
  .then[results=>{
      const productData = results[0].data
      const inventoryData = results[1].data
      let aggregateData = productData
      aggregateData.unitsInStock = inventoryData.unitsInStock
      response.send[aggregateData]
    
  }]
}]

Trong ví dụ này, chúng tôi đang tạo yêu cầu cho hai API bằng cách sử dụng phương thức


01. Chúng tôi chuyển một lần lặp của hai đối tượng
const express = require['express']

// Get the default instance
const axios = require['axios']

const app = express[]

// Express route handler with URL: '/products' and a handler function
app.get['/products', [request, response] => {

  // Make the GET call by passing a config object to the instance
  axios[{
    method: 'get',
    url: '//localhost:3002/products'
  }].then[apiResponse => {
     // process the response
     const products = apiResponse.data
     response.json[products]
  }]
  
}]
1 được trả về bởi hai API làm đầu vào cho phương thức

Đáp lại, chúng tôi nhận được một đối tượng

const express = require['express']

// Get the default instance
const axios = require['axios']

const app = express[]

// Express route handler with URL: '/products' and a handler function
app.get['/products', [request, response] => {

  // Make the GET call by passing a config object to the instance
  axios[{
    method: 'get',
    url: '//localhost:3002/products'
  }].then[apiResponse => {
     // process the response
     const products = apiResponse.data
     response.json[products]
  }]
  
}]
1 duy nhất phân giải thành một mảng kết quả của các đối tượng
const express = require['express']

// Get the default instance
const axios = require['axios']

const app = express[]

// Express route handler with URL: '/products' and a handler function
app.get['/products', [request, response] => {

  // Make the GET call by passing a config object to the instance
  axios[{
    method: 'get',
    url: '//localhost:3002/products'
  }].then[apiResponse => {
     // process the response
     const products = apiResponse.data
     response.json[products]
  }]
  
}]
1 đầu vào

Đối tượng

const express = require['express']

// Get the default instance
const axios = require['axios']

const app = express[]

// Express route handler with URL: '/products' and a handler function
app.get['/products', [request, response] => {

  // Make the GET call by passing a config object to the instance
  axios[{
    method: 'get',
    url: '//localhost:3002/products'
  }].then[apiResponse => {
     // process the response
     const products = apiResponse.data
     response.json[products]
  }]
  
}]
1 này được trả về dưới dạng phản hồi sẽ chỉ giải quyết khi tất cả đầu vào

06 được giải quyết hoặc nếu đầu vào có thể lặp lại không chứa

06

Ghi đè Instance mặc định của Axios

Trong tất cả các ví dụ mà chúng ta đã thấy cho đến nay, chúng ta đã sử dụng

const express = require['express']

// Get the default instance
const axios = require['axios']

const app = express[]

// Express route handler for making a request for fetching a product
app.get['/products/:productName', [request, response] => {

  const productName = request.params.productName  

  axios.get[`//localhost:3002/products/${productName}`]
  .then[apiResponse => {
     const product = apiResponse.data
     response.json[product]
  }]   
}]
4 để lấy một phiên bản của
const express = require['express']

// Get the default instance
const axios = require['axios']

const app = express[]

// Express route handler with URL: '/products/new' and a handler function
app.post['/products/new', async [request, response] => {

  const name = request.body.name
  const brand = request.body.brand

  const newProduct = {name: name, brand:brand}

  // Make the POST call by passing a config object to the instance
  axios[{
    method: 'post',
    url: '//localhost:3002/products',
    data: newProduct,
    headers: {'Authorization': 'XXXXXX'}
  }].then[apiResponse=>{
     const products = apiResponse.data
     response.json[products]
  }]
}]
2 được định cấu hình với các tham số mặc định. Nếu chúng tôi muốn thêm cấu hình tùy chỉnh, chẳng hạn như thời gian chờ là

10 giây, chúng tôi cần sử dụng

11 nơi chúng tôi có thể chuyển cấu hình tùy chỉnh làm đối số

Phiên bản Axios được tạo bằng


11 với cấu hình tùy chỉnh giúp chúng tôi sử dụng lại cấu hình được cung cấp cho tất cả các lệnh gọi API được thực hiện bởi phiên bản cụ thể đó

Dưới đây là một ví dụ về phiên bản

const express = require['express']

// Get the default instance
const axios = require['axios']

const app = express[]

// Express route handler with URL: '/products/new' and a handler function
app.post['/products/new', async [request, response] => {

  const name = request.body.name
  const brand = request.body.brand

  const newProduct = {name: name, brand:brand}

  // Make the POST call by passing a config object to the instance
  axios[{
    method: 'post',
    url: '//localhost:3002/products',
    data: newProduct,
    headers: {'Authorization': 'XXXXXX'}
  }].then[apiResponse=>{
     const products = apiResponse.data
     response.json[products]
  }]
}]
2 được tạo bằng

11 và được sử dụng để thực hiện yêu cầu
const express = require['express']

// Get the default instance
const axios = require['axios']

const app = express[]

// Express route handler with URL: '/products/new' and a handler function
app.post['/products/new', async [request, response] => {

  const name = request.body.name
  const brand = request.body.brand

  const newProduct = {name: name, brand:brand}

  // Make the POST call by passing a config object to the instance
  axios[{
    method: 'post',
    url: '//localhost:3002/products',
    data: newProduct,
    headers: {'Authorization': 'XXXXXX'}
  }].then[apiResponse=>{
     const products = apiResponse.data
     response.json[products]
  }]
}]
8


0

Trong ví dụ này, chúng tôi đang sử dụng


16 để tạo phiên bản Axios mới với cấu hình tùy chỉnh có URL cơ sở là
const express = require['express']

// Get the default instance
const axios = require['axios']

const app = express[]

// Express route handler for making a request for fetching a product
app.get['/products/:productName', [request, response] => {

  const productName = request.params.productName  

  axios.get[`//localhost:3002/products/${productName}`]
  .then[apiResponse => {
     const product = apiResponse.data
     response.json[product]
  }]   
}]
2 và thời gian chờ là

18 mili giây. Cấu hình cũng có một tiêu đề

19 và
const express = require['express']
const axios = require['axios']

const app = express[]

app.get['/products/async/:productName', async [request, response] => {
  const productName = request.params.productName  

  const apiResponse = await axios.get[`//localhost:3002/products/`, {
    params: {
      productName: productName
    }
  }]

  const product = apiResponse.data
  response.json[product]
}]
8 được đặt tùy thuộc vào API được gọi

Cấu hình


21 chỉ định số mili giây trước khi hết yêu cầu. Nếu yêu cầu mất nhiều thời gian hơn khoảng thời gian

21, yêu cầu sẽ bị hủy bỏ

Chặn yêu cầu và phản hồi

Chúng tôi có thể chặn các yêu cầu hoặc phản hồi của lệnh gọi API được thực hiện bằng Axios bằng cách thiết lập các chức năng chặn. Chức năng đánh chặn có hai loại

  • Trình chặn yêu cầu để chặn các yêu cầu trước khi yêu cầu được gửi đến máy chủ
  • Trình chặn phản hồi để chặn các phản hồi nhận được từ máy chủ

Dưới đây là một ví dụ về một phiên bản

const express = require['express']

// Get the default instance
const axios = require['axios']

const app = express[]

// Express route handler with URL: '/products/new' and a handler function
app.post['/products/new', async [request, response] => {

  const name = request.body.name
  const brand = request.body.brand

  const newProduct = {name: name, brand:brand}

  // Make the POST call by passing a config object to the instance
  axios[{
    method: 'post',
    url: '//localhost:3002/products',
    data: newProduct,
    headers: {'Authorization': 'XXXXXX'}
  }].then[apiResponse=>{
     const products = apiResponse.data
     response.json[products]
  }]
}]
2 được định cấu hình với một bộ chặn yêu cầu để nắm bắt thời gian bắt đầu và một bộ chặn phản hồi để tính toán thời gian cần thiết để xử lý yêu cầu


1

Trong ví dụ này, chúng tôi đang đặt


24 thành thời điểm hiện tại trong trình chặn yêu cầu. Trong trình chặn phản hồi, chúng tôi đang nắm bắt thời gian hiện tại trong

25 và tính toán thời lượng bằng cách khấu trừ từ thời gian hiện tại, thời gian bắt đầu được ghi lại trong trình chặn yêu cầu

Thiết bị chặn là một tính năng mạnh mẽ có thể được sử dụng trong nhiều trường hợp sử dụng mà chúng tôi cần thực hiện các hành động chung cho tất cả các lệnh gọi API. Trong trường hợp không có thiết bị chặn, chúng tôi sẽ cần lặp lại các hành động này trong mọi lệnh gọi API. Một số trong những ví dụ này là

  1. Xác minh xem mã thông báo truy cập để thực hiện lệnh gọi API đã hết hạn trong trình chặn yêu cầu chưa. Nếu mã thông báo đã hết hạn, hãy tìm nạp mã thông báo mới bằng mã thông báo làm mới
  2. Đính kèm các tiêu đề cụ thể theo yêu cầu của API vào yêu cầu trong trình chặn yêu cầu. Ví dụ: thêm tiêu đề
    const express = require['express']
    const axios = require['axios']
    
    const app = express[]
    
    app.get['/products/async/:productName', async [request, response] => {
      const productName = request.params.productName  
    
      const apiResponse = await axios.get[`//localhost:3002/products/`, {
        params: {
          productName: productName
        }
      }]
    
      const product = apiResponse.data
      response.json[product]
    }]
    
    8 vào mọi lệnh gọi API
  3. Kiểm tra trạng thái HTTP, tiêu đề và các trường cụ thể trong phản hồi để phát hiện các điều kiện lỗi và kích hoạt logic xử lý lỗi

Xử lý lỗi trong Axios

Phản hồi nhận được từ Axios là JavaScript


27 có chức năng
const axios = require['axios']
axios.get[`//localhost:3002/products/`, {
    params: {
      productName: productName
    }
  }]
  .then[apiResponse => {
     const product = apiResponse.data
     response.json[product]
  }]   
6 để xâu chuỗi lời hứa và chức năng

29 để xử lý lỗi. Vì vậy, để xử lý lỗi, chúng ta nên thêm một hàm

29 vào cuối một hoặc nhiều hàm
const axios = require['axios']
axios.get[`//localhost:3002/products/`, {
    params: {
      productName: productName
    }
  }]
  .then[apiResponse => {
     const product = apiResponse.data
     response.json[product]
  }]   
6 như trong ví dụ này


2

Trong ví dụ này, chúng tôi đã đặt logic xử lý lỗi trong hàm


29. Hàm gọi lại trong

29 lấy đối tượng

34 làm đầu vào. Chúng tôi biết về nguồn gốc của lỗi bằng cách kiểm tra sự hiện diện của thuộc tính

35 và thuộc tính

36 trong đối tượng

34 với

38 và

39

Một đối tượng


34 có thuộc tính

35 cho biết rằng máy chủ của chúng tôi đã trả về lỗi

42 và theo đó trả về một thông báo lỗi hữu ích trong phản hồi

Ngược lại, một đối tượng


34 có thuộc tính

36 biểu thị lỗi mạng, phần phụ trợ không phản hồi hoặc lỗi do yêu cầu trái phép hoặc liên miền gây ra

Đối tượng lỗi có thể không có đối tượng phản hồi hoặc yêu cầu được đính kèm. Điều này cho biết các lỗi liên quan đến việc thiết lập yêu cầu, điều này cuối cùng đã gây ra lỗi. Một ví dụ về tình trạng này là một tham số URL bị bỏ qua khi gửi yêu cầu

Hủy các yêu cầu đã bắt đầu

Chúng tôi cũng có thể hủy hoặc hủy yêu cầu khi chúng tôi không còn yêu cầu dữ liệu được yêu cầu, chẳng hạn như khi người dùng điều hướng từ trang hiện tại sang trang khác. Để hủy yêu cầu, chúng tôi sử dụng lớp AbortController như được hiển thị trong đoạn mã này từ ứng dụng React của chúng tôi


3

Như chúng ta có thể thấy trong ví dụ này, trước tiên chúng ta tạo một đối tượng bộ điều khiển bằng cách sử dụng hàm tạo


45, sau đó lưu trữ một tham chiếu đến đối tượng

46 được liên kết của nó bằng cách sử dụng thuộc tính

47 của

48

Khi yêu cầu

const express = require['express']

// Get the default instance
const axios = require['axios']

const app = express[]

// Express route handler with URL: '/products/new' and a handler function
app.post['/products/new', async [request, response] => {

  const name = request.body.name
  const brand = request.body.brand

  const newProduct = {name: name, brand:brand}

  // Make the POST call by passing a config object to the instance
  axios[{
    method: 'post',
    url: '//localhost:3002/products',
    data: newProduct,
    headers: {'Authorization': 'XXXXXX'}
  }].then[apiResponse=>{
     const products = apiResponse.data
     response.json[products]
  }]
}]
2 được bắt đầu, chúng tôi chuyển vào

46 dưới dạng một tùy chọn bên trong đối tượng tùy chọn của yêu cầu.

51. Điều này liên kết tín hiệu và

52 với yêu cầu
const express = require['express']

// Get the default instance
const axios = require['axios']

const app = express[]

// Express route handler with URL: '/products/new' and a handler function
app.post['/products/new', async [request, response] => {

  const name = request.body.name
  const brand = request.body.brand

  const newProduct = {name: name, brand:brand}

  // Make the POST call by passing a config object to the instance
  axios[{
    method: 'post',
    url: '//localhost:3002/products',
    data: newProduct,
    headers: {'Authorization': 'XXXXXX'}
  }].then[apiResponse=>{
     const products = apiResponse.data
     response.json[products]
  }]
}]
2 và cho phép chúng tôi hủy bỏ yêu cầu bằng cách gọi phương thức

54 trên ________0____52

Sử dụng Axios trong TypeScript

Bây giờ chúng ta hãy xem một ví dụ về việc sử dụng Axios trong các ứng dụng được viết bằng TypeScript

Đầu tiên chúng ta sẽ tạo một thư mục riêng.


56 và tạo một dự án trong Node. js bằng cách chạy lệnh bên dưới bằng cách chuyển vào thư mục này


4

Tiếp theo chúng ta hãy thêm hỗ trợ cho TypeScript vào Nút của chúng ta. js bằng cách thực hiện các bước sau

  1. Cài đặt Typescript và
    
    
    57 với
    const express = require['express']
    
    // Get the default instance
    const axios = require['axios']
    
    const app = express[]
    
    // Express route handler with URL: '/products/new' and a handler function
    app.post['/products/new', async [request, response] => {
    
      const name = request.body.name
      const brand = request.body.brand
    
      const newProduct = {name: name, brand:brand}
    
      // Make the POST call by passing a config object to the instance
      axios[{
        method: 'post',
        url: '//localhost:3002/products',
        data: newProduct,
        headers: {'Authorization': 'XXXXXX'}
      }].then[apiResponse=>{
         const products = apiResponse.data
         response.json[products]
      }]
    }]
    
    0


5

  1. Tạo tệp JSON có tên
    
    
    59 với các nội dung bên dưới trong thư mục gốc của dự án của chúng tôi để chỉ định các tùy chọn khác nhau để biên dịch mã TypeScript


6

  1. Cài đặt mô-đun
    const express = require['express']
    
    // Get the default instance
    const axios = require['axios']
    
    const app = express[]
    
    // Express route handler with URL: '/products/new' and a handler function
    app.post['/products/new', async [request, response] => {
    
      const name = request.body.name
      const brand = request.body.brand
    
      const newProduct = {name: name, brand:brand}
    
      // Make the POST call by passing a config object to the instance
      axios[{
        method: 'post',
        url: '//localhost:3002/products',
        data: newProduct,
        headers: {'Authorization': 'XXXXXX'}
      }].then[apiResponse=>{
         const products = apiResponse.data
         response.json[products]
      }]
    }]
    
    2 với
    const express = require['express']
    
    // Get the default instance
    const axios = require['axios']
    
    const app = express[]
    
    // Express route handler with URL: '/products/new' and a handler function
    app.post['/products/new', async [request, response] => {
    
      const name = request.body.name
      const brand = request.body.brand
    
      const newProduct = {name: name, brand:brand}
    
      // Make the POST call by passing a config object to the instance
      axios[{
        method: 'post',
        url: '//localhost:3002/products',
        data: newProduct,
        headers: {'Authorization': 'XXXXXX'}
      }].then[apiResponse=>{
         const products = apiResponse.data
         response.json[products]
      }]
    }]
    
    0

Axios bao gồm các định nghĩa TypeScript, vì vậy chúng tôi không phải cài đặt chúng riêng biệt

Sau khi kích hoạt dự án cho TypeScript, chúng ta hãy thêm một tệp


62 sẽ chứa mã của chúng ta để thực hiện lệnh gọi API với Axios trong TypeScript

Tiếp theo, chúng tôi sẽ thực hiện một yêu cầu HTTP

const express = require['express']

// Get the default instance
const axios = require['axios']

const app = express[]

// Express route handler with URL: '/products/new' and a handler function
app.post['/products/new', async [request, response] => {

  const name = request.body.name
  const brand = request.body.brand

  const newProduct = {name: name, brand:brand}

  // Make the POST call by passing a config object to the instance
  axios[{
    method: 'post',
    url: '//localhost:3002/products',
    data: newProduct,
    headers: {'Authorization': 'XXXXXX'}
  }].then[apiResponse=>{
     const products = apiResponse.data
     response.json[products]
  }]
}]
8 tới API của chúng tôi để tìm nạp
const express = require['express']
const axios = require['axios']

const app = express[]

app.get['/products/async/:productName', async [request, response] => {
  const productName = request.params.productName  

  const apiResponse = await axios.get[`//localhost:3002/products/`, {
    params: {
      productName: productName
    }
  }]

  const product = apiResponse.data
  response.json[product]
}]
0 như được hiển thị trong đoạn mã này


7

Trong ví dụ này, chúng tôi nhận phiên bản

const express = require['express']

// Get the default instance
const axios = require['axios']

const app = express[]

// Express route handler with URL: '/products/new' and a handler function
app.post['/products/new', async [request, response] => {

  const name = request.body.name
  const brand = request.body.brand

  const newProduct = {name: name, brand:brand}

  // Make the POST call by passing a config object to the instance
  axios[{
    method: 'post',
    url: '//localhost:3002/products',
    data: newProduct,
    headers: {'Authorization': 'XXXXXX'}
  }].then[apiResponse=>{
     const products = apiResponse.data
     response.json[products]
  }]
}]
2 bằng cách nhập nó từ mô-đun ở dòng đầu tiên. Chúng tôi đã xác định tiếp theo hai định nghĩa loại.
const express = require['express']
const axios = require['axios']

const app = express[]

app.get['/products/async/:productName', async [request, response] => {
  const productName = request.params.productName  

  const apiResponse = await axios.get[`//localhost:3002/products/`, {
    params: {
      productName: productName
    }
  }]

  const product = apiResponse.data
  response.json[product]
}]
7 và

67

Sau đó, chúng tôi đã xác định một phương thức


68 trong đó chúng tôi đang gọi API bằng phương thức
const express = require['express']
const axios = require['axios']

const app = express[]

app.post['/products', async [request, response] => {

    const name = request.body.name
    const brand = request.body.brand

    const newProduct = {name: name, brand:brand}

    const apiResponse = await axios.post[`//localhost:3002/products/`, newProduct]

    const product = apiResponse.data
    response.json[{result:"OK"}]
}]
4 sử dụng cú pháp
const express = require['express']

// get the default axios instance
const axios = require['axios']

const app = express[]

// Route Handler
app.get['/products/:productName/inventory', [request, response] => {

  const productName = request.params.productName

  // Call the first API for product details
  const productApiResponse = axios
            .get[`//localhost:3002/products/${productName}`]

  // Call the second API for inventory details
  const inventoryApiResponse = axios
            .get[`//localhost:3002/products/${productName}/itemsInStock`]

  // Consolidate results into a single result
  Promise.all[[productApiResponse, inventoryApiResponse]]
  .then[results=>{
      const productData = results[0].data
      const inventoryData = results[1].data
      let aggregateData = productData
      aggregateData.unitsInStock = inventoryData.unitsInStock
      response.send[aggregateData]
    
  }]
}]

1. Chúng tôi đang chuyển URL của điểm cuối API và tiêu đề

19 cho phương thức
const express = require['express']
const axios = require['axios']

const app = express[]

app.post['/products', async [request, response] => {

    const name = request.body.name
    const brand = request.body.brand

    const newProduct = {name: name, brand:brand}

    const apiResponse = await axios.post[`//localhost:3002/products/`, newProduct]

    const product = apiResponse.data
    response.json[{result:"OK"}]
}]
4

Bây giờ chúng ta hãy chạy chương trình này bằng lệnh dưới đây

Chúng tôi đang gọi phương thức.


68 ở dòng cuối cùng trong chương trình, in phản hồi từ API trong thiết bị đầu cuối/bảng điều khiển

Phần kết luận

Trong bài viết này, chúng ta đã xem xét các khả năng khác nhau của Axios. Dưới đây là tóm tắt những điểm quan trọng từ bài báo

Phản hồi Axios là gì?

Phản hồi của Axios

Dữ liệu phản hồi là gì?

Dữ liệu phản hồi có nghĩa là câu trả lời của chủ thể dữ liệu đối với các câu hỏi do Công ty đặt ra khi sử dụng Dịch vụ . Dữ liệu phản hồi được lưu trữ tách biệt với dữ liệu cá nhân còn lại nhưng được liên kết với chủ thể dữ liệu thông qua tài khoản của người đó với bộ xử lý dữ liệu cá nhân.

Dữ liệu phản hồi của Axios có phải là JSON không?

Theo mặc định, responseType được đặt thành 'json' , có nghĩa là Axios sẽ cố phân tích phản hồi dưới dạng JSON.

Axios có trả về một đối tượng JSON không?

Nếu bạn chuyển đối tượng JavaScript làm tham số thứ 2 cho axios. post[], Axios sẽ tự động tuần tự hóa đối tượng thành JSON cho bạn .

Chủ Đề