Michal Vyšinský bio photo

Michal Vyšinský

Enthusiastic developer.
HC Kometa Brno fan


Twitter LinkedIn Github
This post is in 'notes'. It means it is not as structured as usual. This kind of posts are only personal notes about interesting things and problems I encounter.



The problem

While working on on app with separated js frontend and PHP backend (RESTful API) I have encountered a problem with sending an HTTP request with PATCH method. As it was cross-origin request browser sent an HTTP request with OPTIONS method and after that it sent the PATCH request.

The problem was that on the backend was not an OPTIONS request handled correctly. The server has to respond to OPTIONS request with these headers:

  • Access-Control-Allow-Methods
  • Access-Control-Allow-Origin

Solution

The first one’s value defines which methods are allowed - I had to specify ‘PATCH’ and ‘DELETE’ (for future use). The second one verifies the origin of the request. As I use Slim on backend easy solution is following:

$slim->options('/projects/:id', function () {
	$this->application->response
		->headers->set('Access-Control-Allow-Methods', 'DELETE, PATCH');
	$this->sendSuccess([]);
});

Some other notes

  • browser sends an OPTIONS request only for HTTP methods which are intended to change something (POST, PUT, DELETE, PATCH)
  • in the end it is a good security feature :)