2

When I call axios get always goes directly to the catch block displaying a network error in the console, Access to XMLHttpRequest at 'http://13.234.115.246/customers_log.php' from origin 'http://localhost:8080' has been blocked by CORS policy: Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response.

but the status code is 200

Request URL: http://13.234.115.246/customers_log.php Request Method: OPTIONS Status Code: 200 OK Remote Address: 13.234.115.246:80 Referrer Policy: no-referrer-when-downgrade

how to slove this problem

ShrJoshi
  • 325
  • 1
  • 6
  • 13

1 Answers1

2

Before a GET/POST is performed, the webbrowser will first do a "preflight request". That's a request of type OPTIONS, which is intended just to verify which options are allowed/possible.

The preflight request is succesful (i.e. status code 200) but tells you that CORS is not allowed. So, the actual GET/POST/... request will not be executed. Why not?

  • the webserver that hosts your webpages is not the same server as the one that provides the REST services. And that could indicate a security issue.
  • the webserver is configured to notify your client about this.

I guess you are still in development phase. So, you basically you just need to enable CORS on your backend server if you want to allow this.

for node

e.g. you could add something like the following if you use NodeJS.

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

for php

For php see this thread.

bvdb
  • 22,839
  • 10
  • 110
  • 123
  • I am writting this code- axios.get('http://13.234.115.246/customers_log.php',{ headers: { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods':'GET', 'content-type': 'application/json', 'Access-Control-Allow-Credentials': true, }, }) .then(function (response) { // handle success console.log(response); }) .catch(function (error) { // handle error console.log(error); }) – ShrJoshi Apr 11 '19 at 10:02
  • this Origin: ... stuff should not be on your front-end request, it should be on your back-end . i.e. in your php code. --> I added an example for php – bvdb Apr 11 '19 at 10:04
  • As per you say i added this on my backend but still getting same. – ShrJoshi Apr 11 '19 at 10:44
  • @ShrJoshi There is another thread on stackoverflow, which features a giant `cors()` method for your PHP backend which is probably more robust. https://stackoverflow.com/questions/8719276/cors-with-php-headers – bvdb Apr 11 '19 at 13:45
  • thank you now its working i am adding in php heders-: header("Access-Control-Allow-Origin: *"); header("Access-Control-Allow-Headers: *"); – ShrJoshi Apr 12 '19 at 06:17