27👍
Your front and back end are on different ports which means your ajax requests are subject to cross origin security.
You need to set up the back end to accept requests from different origins (or just different port numbers).
Try reading up on CORS and more specifically looking at django cors headers
104👍
Here’s what I did when I got the same error from Django Rest Framework while sending an API request from Restangular.
What this does is add CORS (Cross-Origin Resource Sharing) headers to responses from Django Rest Framework. Not having CORS headers was the cause of the error.
In the Django Project root folder (where the manage.py file is located), do:
pip install django-cors-headers
I tried it using virtualenv but was not able to get it to work, so I installed it without switching to virtualenv and got it installed.
After installing it, you have to make some edits to your django settings.py
INSTALLED_APPS = (
...
'corsheaders',
...
)
MIDDLEWARE_CLASSES = (
...
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
...
)
CORS_ORIGIN_ALLOW_ALL = True
Setting above to true allows all origins to be accepted.
References: https://github.com/ottoyiu/django-cors-headers
- [Django]-What does "'tests' module incorrectly imported" mean?
- [Django]-How to add data into ManyToMany field?
- [Django]-Django dynamic model fields
49👍
In my case, I had simply forgotten to add a trailing slash at the end of the REST API URL. ie,
I had this:
http://127.0.0.1:8000/rest-auth/login
Instead of this:
http://127.0.0.1:8000/rest-auth/login/
- [Django]-How to delete a record in Django models?
- [Django]-How do you set DEBUG to True when running a Django test?
- [Django]-Django download a file
16👍
If using django for backend, you need to do the following 6 things:
-
ensure you are in the virtualenv, then ‘pip install django-cors-headers’
-
add the following in your INSTALLED-APPS section of the settings.py:
‘corsheaders’, -
add the following in the MIDDLEWARE section of the settings.py:
'corsheaders.middleware.CorsMiddleware'
,
'django.middleware.common.CommonMiddleware'
, -
add either of the following at the bottom of the settings.py:
CORS_ORIGIN_ALLOW_ALL = True
orCORS_ORIGIN_WHITELIST = [ 'http://localhost:3000', 'http://127.0.0.1:3000' ]
-
When using CORS_ORIGIN_WHITELIST, use the URL of the front end app where the GET Or POST request is coming from.
-
Another gotcha is ensuring the URL pointing to django ends with a trailing slash.
- [Django]-Cron and virtualenv
- [Django]-Difference between filter with multiple arguments and chain filter in django
- [Django]-What's the best way to extend the User model in Django?
8👍
If django-cors-headers
not resolved the problem try manual add Access-Control-Allow-Origin
like this:
@api_view(['GET'])
def swanger(request):
resutl = {'a': 1}
resp = JsonResponse(resutl)
resp['Access-Control-Allow-Origin'] = '*'
return resp
- [Django]-How to detect Browser type in Django?
- [Django]-What is the Simplest Possible Payment Gateway to Implement? (using Django)
- [Django]-Comma separated lists in django templates
8👍
I faced the same issue.
user3785412‘s answer will work. but, first time it may not work directly because of browser cache. either try in another browser or clear cache before loosing hope.
I had API server in Django 2 hosted on Heroku and Angular 7 Client on Firebase.
I made all changes in settings.py as per user3785412 and still it would not work, wasted almost 3 hours. Then came across on post which suggested cache could be issue. opened in chrome and voila!
Hope this helps! (My first answer here, please go easy)
- [Django]-Django: what is the difference (rel & field)
- [Django]-Ignoring Django Migrations in pyproject.toml file for Black formatter
- [Django]-What is the most efficient way to store a list in the Django models?
3👍
I have observed this error in 3 scenarios:
- When the URL didn’t end with
/
. - When URL had slashes like
//
or///
. - When my server was not working. But after switching it on it worked fine.
- [Django]-What is the best way to upload files in a modern browser
- [Django]-Django import error – no module named django.conf.urls.defaults
- [Django]-Django abstract models versus regular inheritance
2👍
in my case it was localhost:8000 while 127.0.0.1 was expected… changing localhost to 127.0.0.1 in my browser did the trick
- [Django]-Different db for testing in Django?
- [Django]-Django post_save() signal implementation
- [Django]-Django Migrations Add Field with Default as Function of Model
1👍
Add following line in middleware classes
'corsheaders.middleware.CorsPostCsrfMiddleware'
so overall implementation would be:
INSTALLED_APPS = (
...
'corsheaders',
...
)
MIDDLEWARE_CLASSES = (
...
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
'corsheaders.middleware.CorsPostCsrfMiddleware'
...
)
CORS_ORIGIN_ALLOW_ALL = True
check documentaion below for more info
- [Django]-Django-rest-framework 3.0 create or update in nested serializer
- [Django]-Error: Templates should only be responsible for mapping the state to the UI. Avoid placing tags with side-effects in your templates, such as <script>
- [Django]-Auto-create primary key used when not defining a primary key type warning in Django
1👍
Old question, but I’m not seeing this solution, which worked for me, anywhere. So hoping this can be helpful for someone.
Cross-origin requests in this context are only possible if the partner site’s server allows it through their response headers.
I got this to work in Django without any CORS middleware by setting the following headers on the response:
response["Access-Control-Allow-Origin"] = "requesting_site.com"
response["Access-Control-Allow-Methods"] = "GET"
response["Access-Control-Allow-Headers"] = "requesting_site.com"
Most answers on StackOverflow seem to mention the first one, but not the second two. I’ve just confirmed they are all required. You’ll want to modify as needed for your framework or request method (GET, POST, OPTION).
p.s. You can try "*"
instead of "requesting_site.com"
for initial development just to get it working, but it would be a security hole to allow every site access. Once working, you can restrict it for your requesting site only to make sure you don’t have any formatting typos.
- [Django]-How can I upgrade specific packages using pip and a requirements file?
- [Django]-Error: No module named psycopg2.extensions
- [Django]-Django model blank=False does not work?
0👍
i was using python 2.7 and due to some reasons i cannot change the python version
to version 3 and it took me 3 hours to find a solution which is :
response = HttpResponse(json.dumps(result), content_type="application/json")
response["Access-Control-Allow-Origin"] = '*'
response["Access-Control-Allow-Methods"] = 'GET,PUT, OPTIONS'
response["Access-Control-Max-Age"] = '1000'
response["Access-Control-Allow-Headers"] = 'X-Requested-With, Content-Type'
return response
- [Django]-Django: show/log ORM sql calls from python shell
- [Django]-Django AutoField with primary_key vs default pk
- [Django]-Django – why is the request.POST object immutable?
0👍
Add redirect: 'follow'
to the headers on the client
var requestOptions = {
method: 'POST',
headers: myHeaders,
body: raw,
redirect: 'follow'
};
fetch("http://www.example.com/auth/token/login/", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));
- [Django]-When to create a new app (with startapp) in Django?
- [Django]-How do you detect a new instance of the model in Django's model.save()
- [Django]-Django-Admin: CharField as TextArea
0👍
I try the above answers with favs but all not work. When I read again the terminal prompts and I found a warning: MIDDLEWARE_CLASSES is not compatible to the debug environment, use MIDDLEWARE
. I found the MIDDLEWARE settings and add 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware',
to it and it worked.
Sigh
- [Django]-Get user profile in django
- [Django]-How to display the current year in a Django template?
- [Django]-Uwsgi installation error in windows 7