16

I'm working on a react app. Where I'm requesting for an API by AXIOS. But When I run NPM START to test my app in localhost I'm getting CORS error. Here is the error Access to XMLHttpRequest at 'https://********.com/trx_status.php' from origin 'http://localhost:3000' has been blocked by CORS policy: Request header field privatekey is not allowed by Access-Control-Allow-Headers in preflight response.

I'm new in react. Please tell me how can I solve this issue. Thank you...

Mustakim
  • 388
  • 2
  • 6
  • 15
  • Possible duplicate of [No 'Access-Control-Allow-Origin' - Node / Apache Port Issue](https://stackoverflow.com/questions/18310394/no-access-control-allow-origin-node-apache-port-issue) – MaartenDev Nov 03 '19 at 10:31

4 Answers4

5

Open package.json file, in directory of your App, then add this line (preferably under "private" line, as you can see in the picture below. This also works for any other url if your back-end is not located on your localhost.

"proxy": "http://localhost:3000/",

Remember to restart your server after this change!

enter image description here

Ali.Ghodrat
  • 3,348
  • 3
  • 31
  • 31
  • While this is a fix for local projects, others might brake due to adding a proxy. For example if you run both instances in docker environments. – David Fischer Jul 13 '22 at 09:25
  • Hey Ali, thank you for this answer. How do you suggest on using this proxy url? when I write my fetch statement, should that fetch statement include this url? – Afaq Ahmed Khan Jun 21 '23 at 11:47
4

The error is caused by the custom privatekey header that is send to the server. This field has to be included in the Access-Control-Allow-Headers response header from the server. It can be done using:

Access-Control-Allow-Headers: privatekey

when using php the following snippet can be used:

header('Access-Control-Allow-Headers: X-Requested-With, privatekey');
MaartenDev
  • 5,631
  • 5
  • 21
  • 33
3

This seems to me like an issue at your server side. So what you could try doing is to try adding the header "Access-Control-Allow-Origin: *".

It would be helpful if you could post it somewhere in jsfiddle or some editor so we can look at it further.

Thanks

Vivek V Nair
  • 199
  • 1
  • 3
  • 12
1

For this you will need to allow CORS in your backend code for the URL you will be deploying, and you can use that URL as proxy. You can refer this documentation for detailed instructions.

Ankur Kedia
  • 3,453
  • 1
  • 13
  • 15