11π
TL;DR
Issue your AJAX request to a slash-appended URL.
Explanation
After our discussion, it appears that the culprit is Djangoβs automatic APPEND_SLASH = True
which is enabled when CommonMiddleware
is enabled.
This causes the AJAX request from your Angular app to first hit a 301 Moved Permanently
redirect to the slash-appended URL. However, the corsheaders
middleware does not act on this response, so the browser complains about a missing Access-Control-Allow-Origin
header.
This is solved by requesting the slash-appended URL directly, and bypassing the 301 redirect altogether.
$http({
method: 'GET',
url: 'http://127.0.0.1:8000/xyz/api/abc/', // trailing slash here
cache: false
}).success(...);
0π
Install django-crops-headers
pip install django-cors-headers
In setting.py:
MIDDLEWARE = [
#...
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
]
INSTALLED_APPS = [
'corsheaders',
#...
]
Set CORS_ORIGIN_ALLOW_ALL is True
CORS_ORIGIN_ALLOW_ALL = True # this allows all domains
Or to allow specific domains
CORS_ORIGIN_WHITELIST = (
'http://example.com',
'http://127.0.0.1:8000',
'http://localhost:8000',
)
In Ajax call(front end) add headers:
var get_request = $.ajax({
type: 'GET',
"headers": {
"accept": "application/json",
"Access-Control-Allow-Origin":"*"
},
url: 'http://example.com',
});
If it is not solved, You should enable the core in requesting server(http://example.com)
- [Django]-Django β Alternatives To File Browser that Work Well With S3
- [Django]-Django Rest Framework doesn't accept ArrayField POST
- [Django]-What's your favorite way to test the javascript in your djangoapp?
- [Django]-Showing auth_message's
- [Django]-Type object has not attribute 'get_or_create'