欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

使用axios請求接口,幾種content-type的區(qū)別詳解

 更新時間:2019年10月29日 10:22:47   作者:付出總會有收獲  
今天小編就為大家分享一篇使用axios請求接口,幾種content-type的區(qū)別詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧

axios的使用

安裝(一般使用框架的話, 腳手架都集成了)

$ npm install axios

請求示例

// POST
axios.post('/user', {
 firstName: 'Fred',
 lastName: 'Flintstone'
 })
 .then(function (response) {
 console.log(response);
 })
 .catch(function (error) {
 console.log(error);
 });
// GET
axios.get('/user', {
 params: {
  ID: 12345
 }
 })
 .then(function (response) {
 console.log(response);
 })
 .catch(function (error) {
 console.log(error);
 });
// 執(zhí)行多個并發(fā)
axios.all([get1(), get2()])
 .then(axios.spread(function (acct, perms) {
 // 兩個請求現(xiàn)在都執(zhí)行完成
 }));

可以通過向 axios 傳遞相關配置來創(chuàng)建請求

語法: axios(config)

axios({
 method: 'post',
 url: '/user/12345',
 data: {
 firstName: 'Fred',
 lastName: 'Flintstone'
 }
});

這里, 我就拿以POST的方式傳遞相關配置來說事, 因為筆者在這里躺了兩次坑, 很有必要記錄一下, 哈哈.

默認情況下, 不寫content-type, 是以json的方式來傳遞, (Content-Type: application/json;charset=UTF-8)

axios({
 url:'/api/connect/token',
 method: 'post',
 data: {
   firstName: 'Fred',
   lastName: 'Flintstone'
  }
 }).then(res => {
  console.log(1234, res.data)
 }).catch(error => {
  console.log(error)
 })

Headers如下:

Request Payload
{ firstName: "Fred", lastName: "Flintstone"}

content-type改成x-www-form-urlencoded, 即表單提交方式

axios({
 url:'/api/connect/token',
 method: 'post',
 data: {
   firstName: 'Fred',
   lastName: 'Flintstone'
  },
 headers: {
   'Content-type': 'application/x-www-form-urlencoded'
  }
 }).then(res => {
  console.log(1234, res.data)
 }).catch(error => {
  console.log(error)
 })

Headers如下:

Form Data
{"firstName":"Fred","lastName":"Flintstone"}: 

另一種情況, 序列化成字符串形式傳遞

axios({
 url:'/api/connect/token',
 method: 'post',
 data: JSON.stringify({
   firstName: 'Fred',
   lastName: 'Flintstone'
  })
 }).then(res => {
  console.log(1234, res.data)
 }).catch(error => {
  console.log(error)
 })

結(jié)果跟上面一致:

Form Data
{"firstName":"Fred","lastName":"Flintstone"}: 

還有一種常見情況, 通過qs庫對數(shù)據(jù)進行編碼(前提要安裝qs)

import qs from 'qs'
axios({
 url:'/api/connect/token',
 method: 'post',
 data: qs.stringify({
   firstName: 'Fred',
   lastName: 'Flintstone'
  })
 }).then(res => {
  console.log(1234, res.data)
 }).catch(error => {
  console.log(error)
 })

結(jié)果:

Request Headers
Content-Type: application/x-www-form-urlencoded
Form Data
firstName: Fred
lastName: Flintstone

使用qs要注意的點 :

allowDots(多層對象嵌套, 可用.標記)

qs.stringify({ 
 a: { 
  b: { 
   c: 'd', e: 'f' 
  } 
 } 
}, { allowDots: true });
// 'a.b.c=d&a.b.e=f'

以上這篇使用axios請求接口,幾種content-type的區(qū)別詳解就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關文章

最新評論