Retrieve data from API REST Django and Angular - python

I'm trying to retrieve the json from the rest api set up using Django.
This data is currently only hosted on: http://127.0.0.1:8000/xyz
When I try to retrieve it using
$http({
method: 'GET',
url: 'http://127.0.0.1:8000/xyz',
})
I get an error that is:
XMLHttpRequest cannot load http://127.0.0.1:8000/xyz. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1:8080' is therefore not allowed access.
Can someone tell me a way of dealing with this, please?
Thanks!
Here's my Django settings folder:
INSTALLED_APPS = (
'student',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'corsheaders'
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware'
)
CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_ALLOW_ALL = True
CORS_URLS_REGEX = r'^/api.*$'
CORS_ORIGIN_WHITELIST = (
'mydomain',
'localhost:3000',
'http://127.0.0.1:8000/'
)

Look into using django-cors-headers to have Django return the proper headers. You can then create a whitelist for your site (http://127.0.0.1:8080 for development and whatever your final domain for production)
I use the following on my settings for a similar setup:
INSTALLED_APPS += ('corsheaders',)
CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_ALLOW_ALL = True
CORS_URLS_REGEX = r'^/api.*$'
CORS_ORIGIN_WHITELIST = (
'mydomain',
'localhost:3000',
)
You may also need to add the following to your Angular project:
$http.defaults.useXDomain = true;
[UPDATE]
See this blog for more details

Apart from the changes in settings.py, please try to add a slash at the end of the url you are calling
$http({
method: 'GET',
- url: 'http://127.0.0.1:8000/xyz',
+ url: 'http://127.0.0.1:8000/xyz/',
})

Related

django cors headers not working (yes ik a 100th people asked before but their solutions didn't work)

my settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'channels',
'chatterapi',
'chatterchannels',
"corsheaders",
]
MIDDLEWARE = [
"corsheaders.middleware.CorsMiddleware",
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
CORS_ALLOW_ALL_ORIGINS: True
*the chatter apps are my apps, and i'm also using django channels. tried moving cors headers up and down but had no luck.
idk how to get the actual headers but here is the log :
my views.py ?
#api_view(['POST'])
def createRoom(request):
key = get_random_string(15)
request.POST._mutable = True
request.data['key'] = key
request.POST._mutable = False
print(request.data)
serializer = RoomSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
else:
return Response(serializer.errors, status=400)
I really don't know what's going on, let me know if there is any way I can help.
Is it possible that django channels overriding the runserver command is causing a conflict or something? (if that sounds dumb, please forgive me, cause I AM dumb)
You use the wrong syntax for setting a variable value. Change the line
CORS_ALLOW_ALL_ORIGINS: True
to
CORS_ALLOW_ALL_ORIGINS = True
Sometimes the below code may not work
CORS_ALLOW_ALL_ORIGINS = True
Try mentioning the hosts manually like below
CORS_ALLOWED_ORIGINS = [
"http://localhost:3000",
"http://localhost:8000",
]

Django CORS allowing requests from non-allowed origin

I have Django CORS running with an allowed origin list that looks like this:
CORS_ORIGIN_ALLOW_ALL = False
CORS_ALLOWED_ORIGINS = [
'http://127.0.0.1:8000',
'http://127.0.0.1:3000',
]
Yet if I request this using Python's requests library in my terminal it still allows the request. I've even tried only allowing requests from https://google.com, but it still allows me to use my API.
Why is this? (I'm still new to Django, so sorry if this is a bad question)
Here are some other settings
Installed apps:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# internal
'my_app1',
'my_app2',
'my_app3',
# third party
'rest_framework',
'corsheaders',
'debug_toolbar',
]
Middleware:
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
'debug_toolbar.middleware.DebugToolbarMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django_user_agents.middleware.UserAgentMiddleware',
]
From mozilla CORS docs
Cross-Origin Resource Sharing (CORS) is a mechanism that uses
additional HTTP headers to tell browsers to give a web application
running at one origin, access to selected resources from a different
origin.
It is browser mechanism and has nothing to do with API protection in sense you are misinterpreting it

¿Why my CORS config in django is not working?

I have my REST API settings in my production.py file. This REST API is uploaded to Heroku and uses django-cors-headers with the following configuration:
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# Third-Party apps
'rest_framework',
'rest_framework.authtoken',
'corsheaders',
'gunicorn',
# Local apps
'core',
'users',
'checkers',
]
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
]
CORS_ORIGIN_ALLOW_ALL = False
CORS_ORIGIN_WHITELIST = (
'myapi.herokuapp.com'
)
The idea when putting myapi.herokuapp.com in CORS_ORIGIN_WHITELIST is to see if making the request from localhost is rejected (it would be the right thing to do). But this is accepted which gives me to understand that CORS is not working well.
before fetch the django rest_api, make sure you setup django-cors-headers in your backend settings.py. for more information take a look at this link.
pip install django-cors-headers
settings.py :
INSTALLED_APPS = [
...
'corsheaders',
...
]
MIDDLEWARE = [ # Or MIDDLEWARE_CLASSES on Django < 1.10
...
'corsheaders.middleware.CorsMiddleware',
'corsheaders.middleware.CorsPostCsrfMiddleware',
...
]
CORS_ORIGIN_ALLOW_ALL = False
CORS_ORIGIN_WHITELIST = (
'your-server-IP-address'
)
CORS_ALLOW_METHODS = [
'DELETE',
'GET',
'OPTIONS',
'PATCH',
'POST',
'PUT',
]

django-cors-headers settings.py django app not working even though I've added all the requirements to settings.py

So, I'm using django-cors-headers with Rest Framework with Django 1.11.x, and I've pretty much followed the general advice, and yet, I'm still getting x has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource." As you can see, I've added 'corsheaders' to INSTALLED_APPS and 'corsheaders.middleware.CorsMiddleware' to Middleware, and I've set CORS_ORIGIN_ALLOW_ALL to true and CORS_ALLOW_CREDENTIALS to true, too. I've even included a whitelist option, though it's my understanding that, if CORS_ORIGIN_ALLOW_ALL is set to true, the whitelist isn't needed. I've also pip3 install django-cors-headers. What is the deal??? BTW, I've read the README on the django-cors-headers repo. I want to know why it's not working.
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'corsheaders',
'books.apps.BooksConfig',
]
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = True
CSRF_TRUSTED_ORIGINS = (
'localhost:5555'
)
And my js file that's accessing from localhost:5555 is:
var request = $.ajax({
type: 'GET',
url: url,
dataType: 'json',
xhrFields: {
withCredentials: true
}});

Django admin raises CSRF verification failed

I've started new django project and enabled admin app.
I can login to admin site but when I'm trying to add/change site or user I'm getting
CSRF verification failed. Request aborted.
Reason given for failure:
CSRF token missing or incorrect.
That's what I have in settings.py:
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
# Uncomment the next line for simple clickjacking protection:
# 'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
# Uncomment the next line to enable admin documentation:
# 'django.contrib.admindocs',
)
When I'm looking at admin page source I see
<input type='hidden' name='csrfmiddlewaretoken' value='T9Mfk1LRXi5jPE2dh5jcvdKwzYM6Iy5I' />
there
I have Django version 1.4.1
Have you overridden the CSRF_COOKIE_DOMAIN setting? If the CSRF token is present in the form, and you haven't modified the source of the admin app, then the most likely scenario is that the cookie is not being set correctly.
Check the response headers of the login page to make sure that the cookie is being set correctly, and check the request headers of your login attempt to ensure that it is also being sent (and matches the value in the form).
Locally, I have one project where the CRSF works fine when browsing http://localhost:8040/my-admin/ but fails at http://127.0.0.1:8040/my-admin/.
I'm not sure why but that might help save someone some time.
Note: I haven't set the CSRF_COOKIE_DOMAIN.

Categories

Resources