General

Response to preflight request doesn’t pass access control check: It does not have HTTP ok status.

I understand this is a very common error of CORS which whenever using any API, this error comes. I too struggled a lot in my early days with this error, I have seen many solutions on the internet, no one was working, It doesn’t matter, I am finally going to give a very easy solution to this in this article.

What is CORS

So now we understand a little what is CORS

Cross-origin resource sharing (CORS) is a browser security feature that restricts cross-origin HTTP requests that are initiated from scripts running in the browser. If your REST API’s resources receive non-simple cross-origin HTTP requests, you need to enable CORS support

cross-origin HTTP request is one that is made to:

  • A different domain (for example, from example.com to learncodezone.com).
  • A different subdomain (for example, from example.com to web.example.com)
  • A different port (for example, from example.com to example.com:10777)
  • A different protocol (for example, from https://example.com to http://example.com)

Here you should pay attention to the error (It does not have HTTP ok status.) which is seen in the title. Meaning here HTTP status is not ok

Enable CORS support

How can you enable CORS support depends on your API’s integration type.

  • Includes an Origin header.
  • Uses the OPTIONS method.
  • Includes the following headers:
    • Access-Control-Allow-Methods
    • Access-Control-Allow-Headers
    • Access-Control-Allow-Origin

PHP

For php we have create the file in Microsoft Wordpad or Notepad or whatever code editor you are using and save it to the name .htaccess . The filename has just an extension with NO name before the dot.

Like:

Now it is to copy the code given below and paste it in .htaccess file.

<IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin "*"
	Header set Access-Control-Allow-Headers "Access-Control-Allow-Headers , X-Requested-With, Content-Type, Authorization"
	Header set Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"
    Header set Cache-Control "no-cache, no-store, must-revalidate"
    Header set Pragma "no-cache"
    Header set Expires 0
</IfModule>

 Ok so far it is done now we have to go to the web api file and paste this code at the top.

$method = $_SERVER['REQUEST_METHOD'];
if ($method == "OPTIONS") {
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method,Access-Control-Request-Headers, Authorization");
header("HTTP/1.1 200 OK");
die();
}

And now both the files have to be saved and run. and your error will be removed

RECOMMENDED ARTICLES





Leave a Reply

Your email address will not be published. Required fields are marked *