-1

first of all: I already found similar problems to mine, but due to the fact that I am an absolute beginner in react and javascript, I was not able to both fully understand and solve my problem with the given tips and explanations.

My Problem: I want to make a fetch request via a given api (not mine), but get the CORS error written above, when I want to include the "Language" header. It appears that I am not allowed to make this request - the preflight response in the browser also shows that. Interesting part is: I get an response, if I make a Curl -X get request with the neccessary header in the command window.

So my question is: why am I allowed to make that request in the command window, but not in the browser? Is there any workaround or do I need to make some setting changes for chrome?`

JFYI, my Code - doesn´t work:

export const Items = () => {
  fetch("https://requestedurl", {
    headers: {
      Accept: "application/json",
      Language: "de",
    },
  }).then((res) => res.json())
    .then((res) => console.log(res));
};

Works in command prompt:

curl -X GET -H "Language: de" https://requestedurl

Thanks for your help :)

Super Kai - Kazuya Ito
  • 22,221
  • 10
  • 124
  • 129
Zodrox
  • 1

1 Answers1

-1

Browsers make a distinction between simple requests and ones that are complex. The distinction mainly boils down to "is it more complex than a <form> tag?".

Because of this, you can't—for example—send a request to a different domain with an Authorization header or in your case Language.

It is the browser that includes this restriction, which is why cURL is not affected. The (API) server can opt-in to allow CORS requests from some or all origins by sending the browser a header.

Properly configured, this will happen:

  1. The browser decides a request is "not simple"
  2. Instead of your request, it executes a HEAD (not GET/POST) request to the other server and tells the server what your site's domain is and any custom headers that you've set.
  3. The other server will send if it's okay if your domain (origin) is allowed to send it requests and also a list of (custom) headers that it will accept.
  4. If the other server gives the green light, the browser will then allow your original GET/POST/(etc) request to go through. Otherwise, you'll see an error like you do currently.

The previously linked article goes in depth on what CORS is. If you have no control over the (API) server, you can't make those changes. One option would be to run a proxy server on your own domain, which will make a request "simple" (as it would no longer be cross origin).

RickN
  • 12,537
  • 4
  • 24
  • 28