亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定

axios請求JSON問題詳解

標簽:
JavaScript

  1. 当参数是JSON对象时,默认的Content-Type是application/json。

    axios.post('/user', {    firstName: 'Fred',    lastName: 'Flintstone'  })  .then(function (response) {    console.log(response);  })  .catch(function (error) {    console.log(error);  });

    此时传递的参数是Request Payload格式{firstName:"Fred",lastName:"Flintstone"}  

    如果出现No 'Access-Control-Allow-Origin' header is present on the requested resource的错误,则是跨域问题。本人喜欢直接配置服务器来解决跨域:例如Nginx配置:Nginx配置跨域请求

  2. 当参数是JSON字符串时,默认的Content-Type是application/x-www-form-urlencoded。

    axios.post('/user', JSON.stringify({    firstName: 'Fred',    lastName: 'Flintstone'  }))  .then(function (response) {    console.log(response);  })  .catch(function (error) {    console.log(error);  });

    此时传递的参数是Form Data格式key : value

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

    如上。其实这是一个无效的数据,key为{"firstName":"Fred","lastName":"Flintstone"},value为空。

  3. 要想使用application/x-www-form-urlencoded格式,需要进行数据转换,虽然有两种方式URLSearchParamsqs两种方式。我更喜欢使用qs库的方式,代码如下:

    axios.interceptors.request.use((req) => {    if (req.method === 'post') {     req.data = qs.stringify(req.data);    }    return req;}, (error) => Promise.reject(error));

    之后使用axios的时候,只需要传递json对象就可以:

    axios.post('/user', {    firstName: 'Fred',    lastName: 'Flintstone'  })  .then(function (response) {    console.log(response);  })  .catch(function (error) {    console.log(error);  });

點擊查看更多內容
TA 點贊

若覺得本文不錯,就分享一下吧!

評論

作者其他優質文章

正在加載中
  • 推薦
  • 評論
  • 收藏
  • 共同學習,寫下你的評論
感謝您的支持,我會繼續努力的~
掃碼打賞,你說多少就多少
贊賞金額會直接到老師賬戶
支付方式
打開微信掃一掃,即可進行掃碼打賞哦
今天注冊有機會得

100積分直接送

付費專欄免費學

大額優惠券免費領

立即參與 放棄機會
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號

舉報

0/150
提交
取消