axios中post請求 json 和 application/x-www-form-urlencoded


前端向后端傳輸數據時,如果是get傳輸,直接傳在url后;如果是post傳輸,則在請求體body中傳輸。

body中的數據格式又有兩種,一種是  json  數據格式,另一種是 字符串。具體要用哪種格式取決於后端入參的格式。

 

如果后端接收json數據類型,post 的 headers 需要設置 { ‘content-type’: ’application/json’ },傳給后端的數據就形如  { ‘name’:’edward’, ‘age’:’25’ } 

 

如果后端接收的是(表單)字符串類型,post 的 headers 需設置  { ‘content-type’: ’application/x-www-form-urlencoded’ },

,傳輸給后端的數據就形如   ‘name=edward&age=25’  

 

   qs   

qs.stringfy() 將對象序列化成URL的形式

axios默認數據格式為json,所以:

1.當后端需要接收json格式的數據時,post請求頭不需要設置請求頭,數據格式也不需要我們去轉換(若數據已經是json);

2.當后端需要接收字符串格式的數據時,我們需要給post請求頭設置{ ‘content-type’: ’application/x-www-form-urlencoded’ },

   這個時候如果我們傳的入參是一個 js 對象,這時候我們就需要用 qs 轉換數據格式,qs具體用法如下:

 安裝模塊:npm  i  qs  -S

復制代碼
import qs from 'qs';
const data = { name:'edward' , age:'25'};  // 我們傳的是 js 對象
const options = {
  method: 'POST',
  headers: { 'content-type': 'application/x-www-form-urlencoded' },
  data: qs.stringify(data),   // 用 qs 將js對象轉換為字符串 'name=edward&age=25'
  url: 'http://www.edward.com'
}; 
axios(options);
復制代碼

 

 我們也可以在封裝axios的時候,給它全局設置qs 

axios.defaults.baseURL = 'https://api.example.com';
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

 

【區分】: JSON.stringfy()  和 qs.stringfy() 

  let  data = { name: 'edward', age: '25' }

  前者:JSON.stringfy(data)  //  ”{ 'name' : 'edward' , 'age' : '25' }”

  后者:qs.stringfy(data)  // 'name=edward&age=25'

【區分】:jQuery 中 $.ajax 的post請求  VS   axios的post 請求的 content-type 默認值

  前者:"application/x-www-form-urlencoded"

  后者:"application/json"

1
2
3
4
5
6
7
8
9
10
$.ajax({
   type: 'POST',
   contentType: 'application/json;charset=utf-8'// 發送的數據類型
   dataType: 'json',   // 接收的數據類型
   url: 'http://www.edward.com',
   data: JSON.stringfy(formData),
   success: function (res) {
      console.log(res.data)
   }
}) 

contentType: 告訴服務器,我要發什么類型的數據

dataType:告訴服務器,我要想什么類型的數據,如果沒有指定,那么會自動推斷是返回 XML,還是JSON,還是script,還是String。

 

注意 :$.ajax() post發送到服務器的數據。將自動轉換為請求字符串格式

如果為對象,如 { name: 'edward', age: '25' },jQuery 將自動轉化為 'name=edward&age=25'

如果為數組,jQuery 將自動為不同值對應同一個名稱。如 {foo:["bar1", "bar2"]} 轉換為 '&foo=bar1&foo=bar2'。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM