0

I have my api in Django and Django REST framework (DRF).

Here is my settings file:

DEBUG = False

ALLOWED_HOSTS = ['http://localhost:3000', 'http://127.0.0.1:3000']



# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'corsheaders',
    'MyApp.apps.MyappConfig',
]


REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSESS': 'rest_framework.permissions.AllowAny',
}

# React's Port : 3000
CORS_ORIGIN_WHITELIST = [
    'http://localhost:3000', 
    'http://127.0.0.1:3000',
]

CORS_ORIGIN_ALLOW_ALL = True

MIDDLEWARE = [
    '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',
    'corsheaders.middleware.CorsMiddleware',
]

I am getting Bad Request (400) Error:

I inspectd Chrome's network tab, here is what I got:

Request URL: http://localhost:8000/api/list
Request Method: GET
Status Code: 400 Bad Request
Remote Address: 127.0.0.1:8000
Referrer Policy: strict-origin-when-cross-origin
Connection: close
Content-Type: text/html
Date: Wed, 11 Aug 2021 13:05:24 GMT
Server: WSGIServer/0.2 CPython/3.8.1
X-Content-Type-Options: nosniff
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
Cache-Control: max-age=0
Connection: keep-alive
Host: localhost:8000
sec-ch-ua: "Chromium";v="92", " Not A;Brand";v="99", "Google Chrome";v="92"
sec-ch-ua-mobile: ?1
Sec-Fetch-Dest: document
Sec-Fetch-Mode: navigate
Sec-Fetch-Site: none
Sec-Fetch-User: ?1
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Mobile Safari/537.36

In React, I am getting:

Access to XMLHttpRequest at 'http://localhost:8000/api/list/' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

What is the problem, what is the reason behind that error ? The API was working, and I did not have that error before.

4 Answers4

1

Moved to 'corsheaders.middleware.CorsMiddleware' under the 'django.contrib.sessions.middleware.SessionMiddleware',

MIDDLEWARE = [
    .....
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'corsheaders.middleware.CorsMiddleware',
    ......
]

if you have specific request header you should write under the CORS_ALLOW_HEADERS.

CORS_ALLOW_HEADERS = (
        'x-requested-with',
        'content-type',
        'accept',
        'origin',
)
jackquin
  • 534
  • 1
  • 7
  • 19
1

Not sure what's your real problem, but I see two problem:

  • ALLOWED_HOSTS must be just a list of hostnames (or ips), no ports or schemas. Django allowed hosts with port number

  • From the CorsMiddleware readme:

    CorsMiddleware should be placed as high as possible, especially before any middleware that can generate responses such as Django's CommonMiddleware or Whitenoise's WhiteNoiseMiddleware. If it is not before, it will not be able to add the CORS headers to these responses.

    Also if you are using CORS_REPLACE_HTTPS_REFERER it should be placed before Django's CsrfViewMiddleware (see more below).

Dharman
  • 30,962
  • 25
  • 85
  • 135
pbacterio
  • 1,094
  • 6
  • 12
0

Add csrf_token to your request as per django's protection againsts Cross Site Request Forgeries link

Kholdarbekov
  • 973
  • 1
  • 10
  • 28
0

As in documentation here https://github.com/adamchainz/django-cors-headers#setup

MIDDLEWARE = [
    ...,
    "corsheaders.middleware.CorsMiddleware",
    "django.middleware.common.CommonMiddleware",
    ...,
]

corsheaders.middleware.CorsMiddleware should be as high as possible and above CommonMiddleware

Krystian K
  • 377
  • 1
  • 3
  • 13