0

I'm messing around with react and trying to make a put request to an api. I'm trying to send my body as content-type application/json but it keeps sending as text/plain. If I add the header "Content-Type" : "application/json" I just get this as the return.

Request header field Content-Type is not allowed by Access-Control-Allow-Headers in preflight response.

I'm using this 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 :)

  • 3
    You are facing CORS misconfiguration, take a look at: "[Request header field Access-Control-Allow-Headers is not allowed by Access-Control-Allow-Headers](https://stackoverflow.com/a/25727411)". – Xarvalus Jun 18 '18 at 22:51
  • @Xarvalus I'm using this public API http://funtranslations.com/api/yoda, therefore, I cannot change the response headers. Is there any way to send my JSON string as application/json without the "Content-Type" header included in my request? – Jafett Puga Jun 18 '18 at 22:57
  • 1
    Content-Type is perfectly okay and should be like it is if you are really working on JSON objects. You have some possibilities to omit CORS issues, take a look here: "[Cors issue with third party api](https://stackoverflow.com/questions/48123816/cors-issue-with-third-party-api)" – Xarvalus Jun 18 '18 at 23:04

1 Answers1

0

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

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

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.

I love this picture to see what is CORS: enter image description here

uzay95
  • 16,052
  • 31
  • 116
  • 182