响应 django CORS 问题

Pan*_*kaj 6 python django reactjs python-3.9

错误详情

在此输入图像描述

单击按钮时生成了两个请求。

到目前为止我搜索了什么?

Axios 通过 Django REST Framework 被 CORS 策略阻止

React 和 django-rest-framework 的 CORS 问题

但无济于事

我在做什么?

从 React 向 DJango API 提交 POST 请求

Django 端设置文件

CORS_ORIGIN_ALLOW_ALL = True
ALLOWED_HOSTS = [
    "http://127.0.0.1:3000", 
    "http://127.0.0.1", 
    "http://localhost:3000", 
    "http://localhost"
]
CORS_ORIGIN_WHITELIST = [
    "http://127.0.0.1:3000", 
    "http://127.0.0.1", 
    "http://localhost:3000", 
    "http://localhost"
]

INSTALLED_APPS = [
    ......,
    "corsheaders"
]

MIDDLEWARE = [
    .........,
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
]
Run Code Online (Sandbox Code Playgroud)

响应 axios 请求

function authenticate() {
    let body = {
        "email": "ac",
        "password": "def"
    };
    const headers = {
        'Access-Control-Allow-Origin': '*',
        'Content-Type': 'application/json',
    }

    axios.post("http://127.0.0.1:8000/login/", body, {
        headers: headers
    })
    .then(function(response) {
        console.log(response.data);
    })
    .catch(function(error) {
        console.log(error);
    });
}
Run Code Online (Sandbox Code Playgroud)

尝试使用 fetch 的另一种方法,但无济于事

function authenticate() {
    let body = {
        "email": "hi",
        "password": "pass"
    };
    const headers = {
        'Content-Type': 'application/json',
    }
    fetch("http://127.0.0.1:8000/login", {
        method: "POST", 
        headers: { 
            "Content-Type": "application/json"
        },
        body: JSON.stringify(body)
    })
    .then(function(response) {
        console.log(response.data);
    })
    .catch(function(error) {
        console.log(error);
    });
}
Run Code Online (Sandbox Code Playgroud)

DJango侧方法

def Login(request):
    if(request.method == "POST"):
        return JsonResponse({"message" : "Invalid credentials"}, status=401)
Run Code Online (Sandbox Code Playgroud)

Pan*_*kaj 4

以下设置对我有用

CORS_ORIGIN_ALLOW_ALL = True
ALLOWED_HOSTS = [
    "127.0.0.1", 
]

CORS_ALLOWED_ORIGINS = [
    "http://127.0.0.1", 
]
CORS_ALLOW_CREDENTIALS = False

INSTALLED_APPS = [
    .....
    "corsheaders"
]


MIDDLEWARE = [
    ......
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
]
Run Code Online (Sandbox Code Playgroud)

  • 请添加对为实现此功能所做的更改的描述。 (2认同)