Summary of axios usage in node. js, node. jsaxios

Source: Internet
Author: User

Summary of axios usage in node. js, node. jsaxios

Axios is an HTTP Library Based on Promise and can be used in browsers and node. js. axios is becoming more and more popular because of its great recommendation. I have encountered some problems when using axios in my recent project. I would like to take this opportunity to summarize the problem. If any error occurs, please leave it blank.

Function

The browser initiates the XMLHttpRequests request.

Initiate an http request at the node Layer

Support Promise API

Intercept requests and responses

Convert request and Response Data

Cancel request

Automatic JSON Data Conversion

The client supports XSRF defense (Cross-Site Request Forgery)

Compatible

Use

Npm
Npm install axios

Bower
Bower install axios

Cdn

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

Initiate a request

GET

Axios. get ('/user? ID = 123 '). then (res => {console.info (res )}). catch (e => {if (e. response) {// The request has been sent, and the server return status code is not 2xx. Console.info (e. response. data) console.info (e. response. status) lele.info (e. response. headers)} else if (e. request) {// The request has been sent, but no response has been received. // e. request is an XMLHttpRequest instance in the browser, // It is an http in node. clientRequest instance console.info (e. request)} else {// an exception occurred when sending the request. The error lele.info ('error', e. message)} lele.info (e. config)}) // equivalent to 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)}) // equals to the following axios ({url: '/user', method: 'post', data: {firstName: 'Mike ', lastName: 'allen '}}). then (res => {console.info (res )}). catch (e => {console.info (e )})

Notes

Params is used to pass parameters using the GET method, and the official document introduces params are the URL parameters to be sent with the request. must be a plain object or a URLSearchParams object. Params sends a request as a parameter in the URL link. It must be a plain object or URLSearchParams object. Plain object is a simple Object created by a common object defined in JSON format or a new Object; URLSearchParams object refers to a practical method that can be defined by the URLSearchParams interface to process the URL query string object. That is to say, the params parameter is/user? ID = 1 & name = mike & sex = male.

When POST is used, data is used for passing parameters, and data is sent as the request body. In this form, PUT, PATCH, and other request methods are also used. Note that the default Request body Type of POST in axios is Content-Type: application/json (popular in JSON format), which is also the most common request body Type, that is to say, serialized json strings are used to pass parameters, for example, {"name": "mike", "sex": "male"}. At the same time, the backend must receive parameters in the form of @ RequestBody. Otherwise, the frontend transmission of parameters is correct and the backend cannot receive the parameters.

If you want to set the Type to Content-Type: application/x-www-form-urlencoded (supported by the browser native), axios provides two methods:

Browser

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

However, not all browsers support URLSearchParams and caniuse.com for compatibility queries. However, there is a Polyfill (polyfill: the code used to implement native APIs not supported by the browser, which can be fuzzy understood as a patch, make sure that polyfill is in the global environment ).

Alternatively, you can use the qs library to format data. By default, you can use the qs library 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

Another common request body type is multipart/form-data (supported by the browser native), which is also a common format for submitting form data. Compared with x-www-form-urlencoded, the latter is the key-value pairs separated by '&' and separated by '=. Non-letter or number characters will be Percent-encoding (URL encoding), which is why this type does not support binary data (should be replaced by multipart/form-data ).

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.