Access-Control-Allow-Origin (CORS origin)

I got a weird message today when trying to use XMLHttpRequest Request

Access to XMLHttpRequest at 'http://192.168.1.6:8002/polls/' from origin 'http://192.168.1.6:8001' has been blocked by CORS policy: Request header field traceparent is not allowed by Access-Control-Allow-Headers in preflight response.

I turns out that i need to turn on some headers on the destination server. This can be fixed by doing with .htaccess

Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Allow-Methods: "GET,POST,OPTIONS,DELETE,PUT"
Header set Access-Control-Allow-Headers: "Accept,traceparent".  (you can customize this list)

Here is the reason behind this. Let say you host a javascript on domain1.com , this script need to make a XMLHttpRequest on domain2.com. For security reason, the browser has implemented a thing call Cross Origin Resource Sharing (Cors) , this means that your browser will ask domain2.com to check if domain1.com is allowed to get data from domain1.com. By default, domain2.com only calls from domain2.com only. To overcome this, we must set the Header to let domain1.com know what it is allowed ( see the example above). There are many level of controls, for example , if domain1.com make some modification in the Http header before sending to domain2.com , we must set the “Access-Control-Allow-Headers”.

For your reference: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

https://pypi.org/project/django-cors-headers/

Leave a Reply

Your email address will not be published. Required fields are marked *