How to resolve Falcon CORS preflight request error

288 Views Asked by At

I'm using falcon_cors v1.4.1 and falcon-cors v1.1.7 to manage the access to the backend API which is hosted in our company's domain. The frontend Angular application is hosted in a different domain (in AWS).

I have the following CORS setup in the backend.

import falcon
from falcon_cors import CORS

cors = CORS(allow_all_origins=True,
            allow_all_headers=True,
            allow_all_methods=True)
API = falcon.API(middleware=[cors.middleware])
API.add_route(CONFIG.ROOT_PATH + '/query/products', QueryProduct())
...

However, when the Frontend tried to query the API https://mycompanydomain.com/query/products, a CORS error was returned:

Access to XMLHttpRequest at 'https://mycompanydomain.com/query/products' 
from origin 'https://mycompany.aws.com' has been blocked by CORS policy: 
Response to preflight request doesn't pass access control check: 
No 'Access-Control-Allow-Origin' header is present on the requested resource.

With allow_all_origins=True, I would assume the preflight request from all the origins would have been allowed. So not sure how to resolve this issue.

1

There are 1 best solutions below

0
M. Akbar Zain On

I have backend API which was accessible with GET, but couldn't be successful with POST, due to PREFLIGHT issue, which incurred CORS blockage.

Thus, in this site, https://newbedev.com/http-request-from-angular-sent-as-options-instead-of-post#:~:text=HTTP%20request%20from%20Angular%20sent%20as%20OPTIONS%20instead,is%20allowed%20from%20a%20particular%20domain%20as%20follows%3A

I have found that, you just simply play with OPTIONS method, which your browser calls to backend for before "ACTUAL" call. this is called Preflight request.

It uses OPTIONS method instead of get/post/put. Thus, this could might help.

If you use Node Js Server:

 if (req.method == "OPTIONS")
    {
        res.writeHead(200, {"Content-Type": "application/json"});
        res.end();
    }

With PHP, I use this code:

if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    header("HTTP/1.1 200 ");
exit;
}

These are my headers in PHP:

header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header("Access-Control-Max-Age: 3600");
header("HTTP/1.1 200");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Methods, Access-Control-Allow-Headers, Authorization, X-Requested-With, Origin");

Note the OPTIONS method in the headers.

That's it.