Dealing with CORS Requests(Access Control Cross Origin)

Mohammad Al Kalaleeb
Nov 7 · 2 min read

we all done it some time, we setup Laravel/Symfony Backend, we build a front-end application with angular/vue and we made some requests with content-type header and voilà this error appeared.

In this article, I’m not interested about the why, just how to fix it.

The first step is to see the problem, when we try to send POST request the web browser determines if the request is safe to send, basically “safe” here means that the request is POST request that doesn’t have any XML/JSON content-type header, or basically any custom header. The exceptions are listed in MDN page here (skip to section “simple requests”).

Now to fix this we need to send what is called “Preflight Request”. What we want the server to send back is a series of headers. In my case this was accomplished by Nginx config adding the following headers:

if ($request_method = ‘OPTIONS’) {
add_header ‘Access-Control-Allow-Origin’ ‘*’;
add_header ‘Access-Control-Allow-Methods’ ‘GET, POST, OPTIONS’;
add_header ‘Access-Control-Allow-Headers’ ‘DNT,User-Agent,X-Requested-With, If-Modified-Since, Cache-Control, Content-Type,Range, Authorization’;
add_header ‘Access-Control-Max-Age’ 1728000;
add_header ‘Content-Length’ 0;
add_header ‘Content-Type’ ‘text/plain; charset=utf-8’;
return 200;
}

Now you have to add this to a location specifically designed to respond with these headers. request it, and the requests are fixed, Now the web browser will not convert the POST requests to OPTIONS and the day is saved.

Mohammad Al Kalaleeb

Software Developer at Yes-Soft.de

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade