简体   繁体   中英

GET request works from browser & Postman but fails from localhost in React App, does the endpoint necessarily have to add access-control-allow-origin?

I am working on a project where I was given an endpoint to get some data. I put that endpoint's url in the browser, and I see JSON as expected. I make the same request in Postman, and I get the expected result. Then, making the request using fetch or axios from localhost in a React app, when I run the app in the browser I get a:

Access to fetch at ' https://providedurl/path ' from origin ' http://localhost:3000 ' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

I just want to make sure there is nothing I can do about this? Is the only solution to have the endpoint be modified to add the Access-Control-Allow-Origin header, or is there something that can be done from the request side?

CORS (Cross-Origin Resource Sharing) is a way for the server to say “I will accept your request, even though you came from a different origin.” This requires cooperation from the server – so if you can't modify the server (eg if you're using an external API), this approach won't work.

Modify the server to add the header Access-Control-Allow-Origin: * to enable cross-origin requests from anywhere (or specify a domain instead of *). This should solve your problem.

But you are able to access it in Postman and browsers, if you can disable the CORS in browser level it will work.

Disable CORS in Chrome:

  1. Create a new shortcut for the chrome browser and rename to "anyname(disablecors)"

  2. Right click on new created shortcut and select properties

  3. Create a folder in your system with any name(tempchrome).

  4. Select shorcut tab and add target as ""[PATH_TO_CHROME]\\chrome.exe" --disable-web-security --disable-gpu --user-data-dir= "path of the tempchrome""

  5. Click on apply and save.

  6. Open your application in newly created chrome shortcut(disablecors)

Another quick fix in case you have front end running on port 3000 and backend on 5000 is to apply proxy. It goes like this. Put in your client package the following above dependencies:

  "proxy": "http://localhost:5000",

Then make the request relative, NOT absolute. Should work with this setup.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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