Subbu
Subbu

Reputation: 227

Weird behavior of PHP fix for CORS policy

I am developing an application using Angular which runs on port 4200 (localhost). It gets the information from PHP REST API which runs on post 80 (localhost). When I developed a contact us page it was throwing error related to CORS policy which was fixed by placing the following header information in .htaccess file.

Header add Access-Control-Allow-Origin "http://localhost:4200"
Header add Access-Control-Allow-Headers "origin, x-requested-with, content-type"
Header add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"
Header add Access-Control-Max-Age "36000"

The contact us page is working fine now and I am able to post information (queries) and they are updating in the database correctly. But now I have developed register user functionality and I am facing a weird problem here. Sometimes I am seeing the CORS policy issue that

Access to XMLHttpRequest at 'http://localhost/carrentalnew/register' from origin 'http://localhost:4200' 
has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does 
not have HTTP ok status.

So when I get this error, I am going to PHP api program I developed, and entering some info in the middle of the script so that the script fails. For example the following is piece of code where in the middle I entered "hello" so that the script fails.

catch(PDOException $ex) {
  // log connection error for troubleshooting and return a json error response
  error_log("Connection Error: ".$ex, 0);
  $response = new Response();
  $response->setHttpStatusCode(500);
  $response->setSuccess(false);
  $response->addMessage("Database connection error");
  $response->send();
  exit;
}

hello

// handle creating new user
// check to make sure the request is POST only - else exit with error response
if($_SERVER['REQUEST_METHOD'] !== 'POST') {
  $response = new Response();
  $response->setHttpStatusCode(405);
  $response->setSuccess(false);
  $response->addMessage("Request method not allowed");
  $response->send();
  exit;
}

Now I am removing the word "hello" and I am trying to post the register user again and it is working fine and no issues at all. This is a very weird behavior I am seeing. Can any one tell me what mistake I am doing here?

Thanks, Subbu.

Upvotes: 0

Views: 178

Answers (1)

Vinod Sai
Vinod Sai

Reputation: 2122

For cross origin requests, browser sends pre-flight request with Method Options. In that case we have to send response with access control allow origin header

In your case as you have already added in ht access, we can just exit if it is options method

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {    
   return 0;    
}    

As you are sending http error response, browser thinks this is a invalid Cross origin request

Upvotes: 2

Related Questions