Home > Web Front-end > JS Tutorial > Detailed explanation of the steps to use axios (with code)

Detailed explanation of the steps to use axios (with code)

php中世界最好的语言
Release: 2018-04-14 13:47:57
Original
5496 people have browsed it

This time I will bring you a detailed explanation of the steps to use axios (with code), what are the precautions when using axios, the following is a practical case, let's take a look.

Axios is a Promise-based HTTP library that can be used in browsers and node.js. Because of Youda’s recommendation, axios has become more and more popular. I have encountered some problems using axios in recent projects, so I will take this opportunity to summarize them. If there are any mistakes, please feel free to correct them.

Function

The browser initiates an XMLHttpRequests request

The node layer initiates an http request

Support Promise API

Intercepting requests and responses

Convert request and response data

Cancel request

Automatically convert JSON data

The client supports defense against XSRF (cross-site request forgery)

npm
npm install axios

bower
bower install axios

cdn

Initiate a request

GET

axios.get('/user?ID=123')
  .then( res => {
    console.info(res)
  }).catch( e => {
    if(e.response){
    //请求已发出,服务器返回状态码不是2xx。
      console.info(e.response.data)
      console.info(e.response.status)
      console.info(e.response.headers)
    }else if(e.request){
      // 请求已发出,但没有收到响应
      // e.request 在浏览器里是一个XMLHttpRequest实例,
      // 在node中是一个http.ClientRequest实例
      console.info(e.request)
    }else{
      //发送请求时异常,捕捉到错误
      console.info('error',e.message)
    }
    console.info(e.config)
  })
// 等同以下写法
axios({
  url: '/user',
   method: 'GET',
  params: {
    ID: 123
  }
}).then( res => {
  console.info(res)
}).catch( e=> {
  console.info(e)
})
Copy after login

POST

axios.post('/user', {
  firstName: 'Mike',
  lastName: 'Allen'
}).then( res => {
  console.info(res)
}).catch( e => {
  console.info(e)
})
// 等同以下写法
axios({
  url: '/user',
  method: 'POST',
  data: {
    firstName: 'Mike',
    lastName: 'Allen'
  }
}).then( res => {
  console.info(res)
}).catch( e => {
  console.info(e)
})
Copy after login

Precautions

Params are used when passing parameters using the GET method, and the official documentation introduces: params are the URL parameters to be sent with the request. Must be a plain object or a URLSearchParams object. Translated as: params is used as a parameter in the URL link to send the request, and it must be a plain object or URLSearchParams object. Plain object refers to an ordinary object defined in JSON form or new Simple objects created by Object(); while URLSearchParams object refers to a number of utility methods that can be defined by the URLSearchParams interface to handle URLs The query string object, that is to say, the params parameter is passed in the form of /user?ID=1&name=mike&sex=male.

When using POST, the corresponding parameter transfer uses data, and data is sent as the request body. This form is also used for 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), which is also the most common request body type, which means that the serialized json format is used String to pass parameters, such as: { "name" : "mike", "sex" : "male" }; At the same time, the backend must receive parameters in a form that supports @RequestBody, otherwise there will be a situation where the frontend passes the parameters correctly but the backend cannot receive them.

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

Browser side

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

However, not all browsers support URLSearchParams. Check caniuse.com for compatibility, but here is a Polyfill (polyfill: code used to implement native APIs that the browser does not support, which can be vaguely understood as a patch. At the same time, ensure that the polyfill in the global environment).

Alternatively, you can also use the qs library to format the data. By default, the qs library can be used after installing axios.

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

node layer

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

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

Replenish

There is another common request body type, namely multipart/form-data (natively supported by browsers), which is a commonly used format for submitting form data. Compared with x-www-form-urlencoded, the latter is the data encoded as '&' separated key-value pairs, while '=' separates keys and values. Non-alphanumeric or numeric characters will be Percent-encoded (URL encoding), which is why this type does not support binary data (multipart/form-data should be used instead).

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

How to use Angular4 input and output

Add a pop-up dialog box in the WeChat applet

The above is the detailed content of Detailed explanation of the steps to use axios (with code). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template