【问题标题】:Setting Content-Type in fetch request not working在获取请求中设置 Content-Type 不起作用
【发布时间】:2018-01-21 03:40:09
【问题描述】:

我正在向服务器发出远程获取请求。有效载荷是 JSON 格式,所以我想将 Content-Type 标头更改为 application/json。我使用以下代码来执行此操作:

let email = document.getElementById("email").value
let password = document.getElementById("password").value

const body = {"email":email, "password":password}
const headers = new Headers({
    "Content-Type": "application/json",
    "Content-Length": JSON.stringify(body).length
})
const options = {
    method: "POST",
    mode: "no-cors",
    headers: headers,
    body: JSON.stringify(body)
}
console.log(options)
const response = await fetch('http://xx.xx.xx.xxx/login', options)
const json = await response.json()
console.log(json)

但是,在 Chrome 开发者工具控制台中,请求的 Content-Type 标头仍然是 text/plain;charset=UTF-8。我做错了什么?

【问题讨论】:

标签: javascript json reactjs fetch-api


【解决方案1】:

no-cors 请求不允许覆盖 Content-Type 请求标头。

将模式更改为cors

【讨论】:

  • 当然,如果您有一个不支持 CORS 的端点,这完全没用。 :-(
  • @Quentin 是的。只是意味着解决问题需要额外的东西。例如,代理端点,修改标头。或者更改端点以使其执行 CORS。我选择代理端点而不是接触旧的遗留代码。 :-)
  • Here is the relevant section of the documentation for fetch,表示在使用no-cors 模式时,不能为Content-Type 标头设置application/json 的值。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-22
  • 2017-03-29
  • 2023-03-28
  • 2012-08-14
  • 2011-07-28
  • 2017-11-13
相关资源
最近更新 更多