How to use axios in Node.js

Author : xuzhiping   2022-11-11 15:52:46 Browse: 1502
Category : JavaScript

Abstract: This article mainly introduces the summary of the use of axios in node .js, and analyzes the errors encountered in the middle. Ax...

This article mainly introduces the summary of the use of axios in node .js, and analyzes the errors encountered in the middle. Axios is a promise-based HTTP library that can be used in browsers and node .js, and axios is becoming increasingly popular because of its great recommendation.

Function

  • The browser initiates an XMLHttpRequest request
  • The node layer initiates an HTTP request
  • Support for the Promise API
  • Intercept requests and responses
  • Transform request and response data
  • Cancel the request
  • Automatically convert JSON data
  • Client support against XSRF (Cross-Site Request Forgery)

Compatible

Compatible

Use

npm
npm install axios
bower
bower install axios

CND

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

Initiate request

GET

axios.get('/user?ID=123')
  .then( res => {
    console.info(res)
  }).catch( e => {
    if(e.response){
    //The request has been sent, and the status code returned by the server is not 2xx.
      console.info(e.response.data)
      console.info(e.response.status)
      console.info(e.response.headers)
    }else if(e.request){
      // The request was sent but no response was received
      // e.request In the browser, it is an XMLHttpRequest instance,
      // an instance of http.ClientRequest in node
      console.info(e.request)
    }else{
      //an exception was sent while sending the request, and an error was caught
      console.info('error',e.message)
    }
    console.info(e.config)
  })
// It is equivalent to the following writing
axios({
  url: '/user',
   method: 'GET',
  params: {
    ID: 123
  }
}).then( res => {
  console.info(res)
}).catch( e=> {
  console.info(e)
})

POST

axios.post('/user', {
  firstName: 'Mike',
  lastName: 'Allen'
}).then( res => {
  console.info(res)
}).catch( e => {
  console.info(e)
})
// It is equivalent to the following writing
axios({
  url: '/user',
  method: 'POST',
  data: {
    firstName: 'Mike',
    lastName: 'Allen'
  }
}).then( res => {
  console.info(res)
}).catch( e => {
  console.info(e)
})

Note

Params is used when passing parameters using the GET method, And the official document introduces it as: params are the URL parameters to be sent with the request, and it must be a plain object or a URLSearchParams object. Translated as: params sends the request as a parameter in the URL link, it must be a plain object or a URLSearchParams object. Plain object refers to a normal object defined in JSON form or a simple object created by new object(); The URLSearchParams object refers to an object that can be defined by the URLSearchParams interface to handle the query string of the URL. That is, params parameters are passed in the form /user?ID=1&name=mike&sex=male.

When using POST, the corresponding parameter is data, which is sent as a request body. This form is also used by PUT, PATCH and other request methods. One thing to note is that The default request body type of POST in axios is Content-Type:application/json (JSON specification is popular), this is also the most common request body type, that is, the serialized JSON format string is used to pass parameters. For example: { "name" : "mike", "sex" : "male" }; meantime The background must receive parameters in the form of supported @RequestBody, otherwise, the front parameter will be passed correctly, but the background will not receive it.

If you want to set the type to Content-Type:application/x-www-form-urlencoded (native browser support), axios provides two ways, as follows:

Browser end

const params = new URLSearchParams();
params.append('param1', 'value1');
params.append('param2', 'value2');
axios.post('/user', params);

However, not all browsers support URLSearchParams, compatibility queries caniuse.com. But here's a polyfill (polyfill: code used to implement native APIs that browsers don't support. It can be vaguely understood as a patch, while ensuring that the polyfill is in the global environment).

Alternatively, you can use QS as a library to format data. By default, the QS library can be used after installing axios.

const qs = require('qs');
axios.post('/user', qs.stringify({'name':'mike'}));

Node layer

Querystring can be used in the node environment. Similarly, you can use qs to format data.

const querystring = require('querystring');
axios.post('http://something.com/', querystring.stringify({'name':'mike'}));

Supplement

There is another way to common request body types, that is, multipart/form-data (native browser support). This is a format commonly used to submit form data. In contrast to x-www-form-urlencoded, in the latter, the data is encoded into key-value pairs separated by '&' and separated by '=' keys and values. Non-alphanumeric characters are replaced by Percent-encoding(URL encoding), this is why the type does not support binary data (multipart/form-data should be used instead).

Label :
    Sign in for comments!
Comment list (0)

Powered by TorCMS (https://github.com/bukun/TorCMS).