Detailed steps axios used (with code)

Axios is a Promise of HTTP-based library, you can use the browser and node.js in particular, because much of the recommendation, axios also becoming increasingly popular. Recently used in the project axios also encountered some problems, I take this opportunity to summarize, if wrong, please feel free to correct me.

Features

The browser initiates a request XMLHttpRequests

node layer to initiate http request

Support Promise API

Intercept request and response

Conversion request and response data

Cancellation request

Automatically convert JSON data

Client support defense XSRF (CSRF)

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){

    //请求已发出,服务器返回状态码不是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)

})

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)

})

Precautions

在使用GET方法传递参数时使用的是params,并且官方文档中介绍为:params are the URL parameters to be sent with the request. Must be a plain object or a URLSearchParams object。译为:params作为URL链接中的参数发送请求,且其必须是一个plain object或者是URLSearchParams object。plain object(纯对象)是指用JSON形式定义的普通对象或者new Object()创建的简单对象;而URLSearchParams object指的是一个可以由URLSearchParams接口定义的一些实用方法来处理 URL 的查询字符串的对象,也就是说params传参是以/user?ID=1&name=mike&sex=male形式传递的。

而在使用POST时对应的传参使用的是data,data是作为请求体发送的,同样使用这种形式的还有PUT,PATCH等请求方式。有一点需要注意的是,axios中POST的默认请求体类型为Content-Type:application/json(JSON规范流行),这也是最常见的请求体类型,也就是说使用的是序列化后的json格式字符串来传递参数,如:{ "name" : "mike", "sex" : "male" };同时,后台必须要以支持@RequestBody的形式接收参数,否则会出现前台传参正确,后台接收不到的情况。

如果想要设置类型为Content-Type:application/x-www-form-urlencoded(浏览器原生支持),axios提供了两种方式,如下:

浏览器端

const params = new URLSearchParams();

params.append('param1', 'value1');

params.append('param2', 'value2');

axios.post('/user', params);

不过,并不是所有浏览器都支持URLSearchParams,兼容性查询caniuse.com,但是这里有一个Polyfill (polyfill:用于实现浏览器并不支持的原生API的代码,可以模糊理解为补丁,同时要确保polyfill在全局环境中)。

或者,你也可以用qs这个库来格式化数据。默认情况下在安装完axios后就可以使用qs库。

const qs = require('qs');

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

node层

在node环境中可以使用querystring。同样,也可以用qs来格式化数据。

const querystring = require('querystring');

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

补充

常见的请求体类型还有一种方式,即multipart/form-data(浏览器原生支持),也就是提交表单数据常用的一种格式。和x-www-form-urlencoded对比起来,后者则是数据被编码成以 '&' 分隔的键-值对, 同时以 '=' 分隔键和值。非字母或数字的字符会被Percent-encoding(URL encoding),这也就是为什么这种类型不支持二进制数据的原因 (应使用 multipart/form-data 代替)。

Guess you like

Origin www.cnblogs.com/newcityboy/p/12099898.html