【问题标题】:Fetch API - Content-Type is sent as text/plain when it's set to application/json [duplicate]Fetch API - Content-Type 在设置为 application/json 时以 text/plain 形式发送 [重复]
【发布时间】:2019-01-11 09:26:15
【问题描述】:

在我的 React 应用程序中,当我提交表单以创建新用户时,我使用 fetch 创建了对服务器的请求。

代码是这个:

fetch('http://0.0.0.0:3000/users', {
  method: 'POST',
  mode: 'no-cors',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify(data)
}).then(response => console.log(response))

当我检查开发人员工具下的网络选项卡中的条目时,我看到内容类型是 text/plain,但我不明白为什么我将其设置为 application/json。

我尝试在请求中使用选项Edit and send 并将text/plain 替换为application/json,但发送后它以text/plain 发送。

【问题讨论】:

  • 如果您设置 no-cors 是因为您收到 "No Access-Control-Allow-Origin header is present..." 错误,这不是解决方案

标签: javascript fetch-api


【解决方案1】:

mode:"no-cors" 选项是罪魁祸首。

删除该选项,它应该可以工作

要修复它,请传递一个新的标头对象

headers: new Headers({'content-type': 'application/json'})

【讨论】:

  • 我仍然得到相同的结果
  • 更新答案。
  • headers 选项也接受普通对象。它不需要是Headers的实例
  • no-cors 解决了我的问题。谢谢..
  • 对我来说,“cors”模式很有帮助,因为我在其他域上有 API
猜你喜欢
  • 2022-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多