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

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

獲取:POST json數據

獲?。篜OST json數據

手掌心 2019-08-02 13:03:09
獲?。篜OST json數據我試圖發布一個JSON對象去取.根據我所能理解的,我需要在請求的主體上附加一個字符串對象,例如:fetch("/echo/json/",{     headers: {       'Accept': 'application/json',       'Content-Type': 'application/json'     },     method: "POST",     body: JSON.stringify({a: 1, b: 2})}).then(function(res){ console.log(res) }).catch(function(res){ console.log(res) })使用時jsfiddle‘s json回聲我希望看到我發送的對象({a: 1, b: 2})返回,但這并沒有發生-ChromeDevTools甚至沒有將JSON顯示為請求的一部分,這意味著它沒有被發送。
查看完整描述

3 回答

?
紅顏莎娜

TA貢獻1842條經驗 獲得超13個贊

在搜索引擎中,我最后討論了非json使用FETCH發布數據的主題,所以我想添加以下內容。

非JSON您不必使用表單數據。您可以簡單地設置Content-Type頭到application/x-www-form-urlencoded并使用字符串:

fetch('url here', {
    method: 'POST',
    headers: {'Content-Type':'application/x-www-form-urlencoded'}, // this line is important, if this content-type is not set it wont work
    body: 'foo=bar&blah=1'});

另一種方法body字符串,而不是像我上面所做的那樣鍵入它,是使用庫。例如,stringify功能來自query-stringqs包裹。因此,如果使用這個,它看起來就像:

import queryString from 'query-string';fetch('url here', {
    method: 'POST',
    headers: {'Content-Type':'application/x-www-form-urlencoded'}, // this line is important, if this content-type is not set it wont work
    body: queryString.stringify({for:'bar', blah:1}});




查看完整回答
反對 回復 2019-08-05
  • 3 回答
  • 0 關注
  • 1230 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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