简体   繁体   English

PUT 请求正文为 application/json 而不是纯文本/文本

[英]PUT request body as application/json instead of plain/text

I'm messing around with react and trying to make a put request to an api.我正在搞乱反应并试图向 api 发出放置请求。 I'm trying to send my body as content-type application/json but it keeps sending as text/plain.我试图将我的身体作为内容类型的应用程序/json 发送,但它一直以文本/纯文本的形式发送。 If I add the header "Content-Type" : "application/json" I just get this as the return.如果我添加标题 "Content-Type" : "application/json" 我只是把它作为回报。

Request header field Content-Type is not allowed by Access-Control-Allow-Headers in preflight response.预检响应中的 Access-Control-Allow-Headers 不允许请求标头字段 Content-Type。

I'm using this api : http://funtranslations.com/api/yoda我正在使用这个 api: http : //funtranslations.com/api/yoda

Here is my request:这是我的要求:

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

Thank you in advance for attempting to help me :)预先感谢您尝试帮助我:)

I think you are sending data in wrong content-type.我认为您以错误的内容类型发送数据。 According to funtranslation web site content-type should be application/x-www-form-url-encoded根据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 is clearly explaining CORS issue这个地址清楚地解释了 CORS 问题

For cross-domain requests, setting the content type to anything other than application/x-www-form-urlencoded, multipart/form-data, or text/plain will trigger the browser to send a preflight OPTIONS request to the server.对于跨域请求,将内容类型设置为 application/x-www-form-urlencoded、multipart/form-data 或 text/plain 以外的任何内容将触发浏览器向服务器发送预检 OPTIONS 请求。

I love this picture to see what is CORS:我喜欢这张照片,看看什么是 CORS: 在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM