Preflighted HTTP requests

Undestanding CORS

Posted by Alex Ferrer on 8 months ago

In this post, I would like to talk about preflighted HTTP requests and the reasons why to use them. Also I will explain how to manage the following Javascript errors in the browser console when trying to send a request to a webservice.

Failed to load mydomain.com: Response for preflight has invalid HTTP status code..

First of all we should know what is the meaning of CORS acronym.


What is CORS?

Cross-Origin Resource Sharing (CORS) is a mechanism that uses additional HTTP headers to tell a browser to let a web application running at one origin (domain) have permission to access selected resources from a server at a different origin. A web application makes a cross-origin HTTP request when it requests a resource that has a different origin (domain, protocol, and port) than its own origin.


What kind of HTTP exists?

In HTTP we have several types of request. If you want more information about this, you should check the section 'Examples of access control scenarios' in Mozilla.org documentation.

In summary, I checked that it can be requests with and without preflighting: Simple requests and preflighted.

Simple requests (Without Preflighting)

If the origin of the request is allowed in server side and they have the following allowed methods and content-types, them could be triggered without problems.

  • Allowed methods: GET, POST, HEAD.
  • Allowed Content-type headers: 
    • application/x-www-form-urlencoded
    • multipart/form-data
    • text/plain

Resultado de imagen de Preflighted requests

Preflighted requests

These are a bit diferent, because preflighted requests send first a request with an OPTIONS method to the resource of the domain. With this OPTIONS request, server will check all sent headers, if all required headers are in the first OPTIONS request, it will serve the real requested resource. We will have a preflighted request if:

  • If our request has some of these methods: PUT, DELETE, OPTIONS, PATCH, CONNECT, TRACE.
  • If our request has a value other than the following:
    • application/x-www-form-urlencoded
    • multipart/form-data
    • text/plain

Then, as we can see above, if we are sending requests to an external api in our Ionic application and these are using application/json in content-type header and will be preflighted and not simple requests.

I think it's important to use these kind of preflighted requests and not send json documents as text/plain to the server. Using this, we could improve a next level of security in our middleware or backend.

Resultado de imagen de Preflighted requests

Share this post!