首页 > 解决方案 > Fetch API - Content-Type 在设置为 application/json 时以 text/plain 形式发送

问题描述

在我的 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))

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

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

标签: javascriptfetch-api

解决方案


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

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

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

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

推荐阅读