首页 > 解决方案 > 错误请求 400 - Django REST 框架

问题描述

我在 Django 和 Django REST 框架 (DRF) 中有我的 api。

这是我的设置文件:

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',
]

我收到错误请求 (400) 错误:

我检查了 Chrome 的网络选项卡,这是我得到的:

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

在 React 中,我得到:

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.

问题是什么,该错误背后的原因是什么?API 工作正常,我之前没有出现过这个错误。

标签: pythonreactjsdjangodjango-rest-frameworkdjango-views

解决方案


移至'corsheaders.middleware.CorsMiddleware''django.contrib.sessions.middleware.SessionMiddleware',

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

如果您有特定的请求标头,则应在CORS_ALLOW_HEADERS.

CORS_ALLOW_HEADERS = (
        'x-requested-with',
        'content-type',
        'accept',
        'origin',
)

推荐阅读