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 Answer 1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks but how should be solved? I've added this: 'Access-Control-Allow-Origin': '*' but still the same error.
I've read that CORS is declared by server. Thanks!
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.
@AliBahaari you are welcome. also you may see this post link, the post well described how it works.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.