0

I can request to a API very easily in Postman. But when I try it with React JS and on localhost:3000, it throws me an error:

enter image description here

Please tell me why?! Thanks

1 Answers1

2

See https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS/ If you know CORS problems, it would be easier to explain.

Because the requests sent by Postman or ones by your React.JS are kind of different. As you send requests with Postman directly, the requests are considered sent by as "a person", like you enter the URLs of your APIs in your browser.

It's different with sending requests with React because React is a front-end JavaScript based framework language "executed" by your browser. Imaging if you happen to access a malicious web-site, and the site sends intended codes of React(or some JavaScript) to manipulate your browser(An easy example: If there are no limits, it can use your browser as a web crawler to other sites).

You know that every time you open a site, your browser is executing lots of codes from the site.

So you may have to understand why we need CORS policy, and how CORS works to develop your APIs.

Green Sung
  • 71
  • 4
  • 1
    Thanks but how should be solved? I've added this: ```'Access-Control-Allow-Origin': '*'``` but still the same error. –  May 14 '21 at 02:22
  • I've read that CORS is declared by server. Thanks! –  May 14 '21 at 02:29
  • 1
    If you are in development, you can set up your API to allow some special domains that can pass the policy. Most frameworks that support back-end API(e.g. Laravel/Rails) have corresponding methods to do this, but I don't know what back-end you use, You may need to figure it out yourself. Or your can just put your website in the exact machine of your APIs(or any method make your host domain of front-end sites consistent with your APIs) so your React only sends request to the same domain. – Green Sung May 14 '21 at 02:34
  • @AliBahaari you are welcome. also you may see this post [link](https://stackoverflow.com/questions/10636611/how-does-access-control-allow-origin-header-work), the post well described how it works. – Green Sung May 14 '21 at 02:35