簡體   English   中英

為什么 header 中的內容類型仍然是 text/plain 雖然我將其設置為 application/json

[英]Why content-type in header remains text/plain though I set it as application/json

我使用 fetch() 發布 json 數據如下

var data = {
            name: this.state.name,
            password: this.state.password
        }
fetch('http://localhost:3001/register/paitent', {
            method: 'POST',
            body: JSON.stringify(data), 
            mode: 'no-cors',
            headers: new Headers({
                'Content-Type': 'application/json'
            })
        })
        .then(res => res.json())

我總是在我的快速服務器路由器的 request.body 中得到 {},我發現問題出在發送請求中,它總是“文本/純文本”。 為什么會發生這種情況?

在此處輸入圖像描述

您將模式設置為no-cors

將Content-Type設置為application/json需要獲得CORS的許可…

Content-Type標頭(不觸發預檢CORS請求)的唯一允許值為:

  • 應用程序/ x-WWW窗體-urlencoded
  • 多部分/格式數據
  • 純文本/

mdn

......你告訴fetch不問。 由於您不請求許可,因此您也沒有獲得許可,因此訪存將恢復為text/plain

我被困在同一個問題上幾個小時現在找出確切的解決方案,正如 expressjs @Quentin 的文檔中提到的那樣,已經指出了確切的問題。 在這里,我發布了更多詳細信息,可能會幫助其他人快速解決問題。

When you are posting json object with 'Content-Type':'application/json' fetch or any other method browser will request for cors setting first for security reason then if it receives cors options which is very easy to achieve. 然后它將原始 object 發布到服務器,因為 nodejs 服務器正在等待 'Content-Type':'application/json'

您可以在 expressjs.com 上查看 cors 設置的文檔

您只需安裝 cors package 並將此行添加到您的文件中

app.options("/data",cors());

這將為您的瀏覽器設置針對特定路徑/數據的預檢 cors 響應,然后您的方法將如下所示 'app.post('/data',cors(),function(req,res){}'

現在您可以使用 'Content-Type':'application/json' 發布數據

我建議閱讀 MDN 上的 cors 文章以便更好地理解

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM