I was trying to get a CORS request working. With the following JS code I get this error: XMLHttpRequest cannot load http://localhost:65491/?token=u80h9kil9kjuu02539buak4r6n&user=~me. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1:50303' is therefore not allowed access.
this is the JS code:
$.ajax({
url: "http://localhost:60906/",
data: {token : 'u80h9kil9kjuu02539buak4r6n', user : '~me'},
type: "GET",
crossDomain: true,
success: function( response ) {
alert('Success!' + response);
var context = response;
}
});
When I look at the network using chrome's devtools I see that there is no 'Access-Control-Allow-Origin'
header indeed. But when I load the site manually it is present!
I used the following code to set the headers:
response = JsonResponse(simpleWeek)
response['Access-Control-Allow-Origin'] = '*'
return response
hoping for some help!
A web browser compares the Access-Control-Allow-Origin with the requesting website's origin and permits access to the response if they match. The cross-origin resource sharing (CORS) specification prescribes header content exchanged between web servers and browsers that restricts origins for web resource requests outside of the origin domain.
Steps to allow CORS in your Django Project – 1. Install django-cors-headers using PIP: pip install django-cors-headers 2. Add corsheaders to installed applications section in the settings.py file: INSTALLED_APPS = [ ... 'corsheaders',... 3. Add corsheaders.middleware.CorsMiddleware to middleware ...
In this section we explain what the Access-Control-Allow-Origin header is in respect of CORS, and how it forms part of CORS implementation. The cross-origin resource sharing specification provides controlled relaxation of the same-origin policy for HTTP requests to one website domain from another through the use of a collection of HTTP headers.
The browser will allow code running on normal-website.com to access the response because the origins match. The specification of Access-Control-Allow-Origin allows for multiple origins, or the value null, or the wildcard *. However, no browser supports multiple origins and there are restrictions on the use of the wildcard * .
It says No 'Access-Control-Allow-Origin' header is present on the requested resource.
which means your server application needs tunning to accept cross origin requests.
Cross origin requests are by default not working due to security reasons. You need to enable them.
For django there is a maintained package with good amount of settings just for this: https://github.com/ottoyiu/django-cors-headers/
After 2 hours of troubleshooting I found solution: TYPO in url. Check twice, maybe it will fix your issue too.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With