【问题标题】:PUT request body as application/json instead of plain/text将请求正文作为 application/json 而不是纯文本/文本
【发布时间】:2018-11-27 19:52:50
【问题描述】:

我正在搞乱 react 并尝试向 api 发出 put 请求。我正在尝试将我的正文作为内容类型应用程序/json 发送,但它一直以文本/纯文本形式发送。如果我添加标题 "Content-Type" : "application/json" 我只是得到这个作为回报。

预检响应中的 Access-Control-Allow-Headers 不允许请求标头字段 Content-Type。

我正在使用这个 API:http://funtranslations.com/api/yoda

这是我的要求:

fetch('http://api.funtranslations.com/translate/yoda.json', { method: 'PUT', body: JSON.stringify({ text: this.state.input }) })
.then(res => { return console.log(res.json()); }) }

提前感谢您尝试帮助我:)

【问题讨论】:

标签: javascript reactjs fetch-api


【解决方案1】:

我认为您发送的数据内容类型错误。根据funtranslation网站内容类型应该是application/x-www-form-url-encoded

fetch('http://api.funtranslations.com/translate/yoda.json', {
  method: 'PUT',
  headers: {'Content-Type': 'application/x-www-form-url-encoded', 'Accept': 'application/json'},
  body:"text=hadi"
})
.then(res => {
    return console.log(res.json());
})

This address 清楚地解释了 CORS 问题

对于跨域请求,将内容类型设置为 application/x-www-form-urlencoded、multipart/form-data 或 text/plain 以外的任何内容都会触发浏览器向服务器发送预检 OPTIONS 请求.

我喜欢这张照片,看看什么是 CORS:

【讨论】:

    猜你喜欢
    • 2021-11-27
    • 1970-01-01
    • 2020-12-12
    • 2017-02-20
    • 1970-01-01
    • 2018-01-13
    • 2019-02-16
    • 1970-01-01
    相关资源
    最近更新 更多