【问题标题】:Django, Next.JS: CORS header ‘Access-Control-Allow-Origin’ missing, CORS request did not succeed even though django-cors-headers is definedDjango,Next.JS:缺少 CORS 标头“Access-Control-Allow-Origin”,即使定义了 django-cors-headers,CORS 请求也未成功
【发布时间】:2021-01-14 08:11:47
【问题描述】:

我被 Django 和 Next.JS 的 CORS 问题困扰着。 我的设置: 操作系统:Windows 10,浏览器:Mozilla:84.0.2(64 位),Django:3.1,Next.JS:10。

我的 Django 设置:

INSTALLED_APPS = [
    ...
    'corsheaders',
    'rest_framework',
    'my_app',
]

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

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.AllowAny',
    ],
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework_simplejwt.authentication.JWTAuthentication',
    ],
}

CORS_ALLOWED_ORIGINS = [
    'http://localhost:3000',
]

CORS_ORIGIN_ALLOW_ALL = False
CORS_ALLOW_CREDENTIALS = True

urls.py:

from rest_framework_simplejwt.views import (
    TokenObtainPairView,
    TokenRefreshView,
)

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/', include('my_app.urls')),
    path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'),
    path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),
]

我的 Next.js 页面:

import { useState } from 'react';
import axios from 'axios';

export default function loginForm() {
    const [username, setUsername] = useState('');
    const [password, setPassword] = useState('');

    const handleSubmit = () => {
       const headers = {
        "Content-Type": "application/json",
        "Accept": "application/json"
      }
       return axios({
            method: "POST",
            url: "http://127.0.0.1:8000/api/token/",
            data: {
                username: username,
                password: password
             },
             headers: headers
        })
        .then(function (response) {
            console.log(response);
        })
        .catch(function (response) {
            console.log(response);
        });
    };

    return (
        <div className="loginBox">
            <div className="lblBox">
                <label className="label" htmlFor="loginbox">
                    Enter Username and Password
                    <div className="unameInput">
                        <input 
                            type="text"
                            name="username"
                            placeholder='Enter username'
                            onChange={e => setUsername(e.target.value)}
                        />
                    </div>
                    <div className="passwordInput">
                        <input 
                            type='password'
                            name='password'
                            placeholder='Enter password'
                            onChange={e => setPassword(e.target.value)}
                        />
                    </div>
                    <div className="submitBtn">
                        <button onClick={handleSubmit} name='submit'>Submit</button>
                    </div>
                </label>
            </div>
        </div>
    );
}

提交时,我在控制台中收到此错误:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://127.0.0.1:8000/api/token/. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://127.0.0.1:8000/api/token/. (Reason: CORS request did not succeed).

这是 Django 命令行中的输出:

[14/Jan/2021 12:47:56] "OPTIONS /api/token/ HTTP/1.1" 200 0
[14/Jan/2021 13:09:20] "OPTIONS /api/token/ HTTP/1.1" 200 0
[14/Jan/2021 13:26:46] "OPTIONS /api/token/ HTTP/1.1" 200 0

这是控制台中的 XHR 标头:

GET  http://127.0.0.1:3000/_next/static/webpack/4bc7d30193ea5b40fd0f.hot-update.json
Status  200 OK
Version  HTTP/1.1
Transferred  392 B (71 B size)
Referrer Policy  no-referrer-when-downgrade

响应标头

Accept-Ranges: bytes
Cache-Control: public, max-age=0
Connection: keep-alive
Content-Length: 71
Content-Type: application/json; charset=UTF-8
Date: Thu, 14 Jan 2021 07:58:35 GMT
ETag: W/"47-176ffe6686d"
Keep-Alive: timeout=5
Last-Modified: Thu, 14 Jan 2021 07:57:38 GMT
Vary: Accept-Encoding

请求标头

Accept: */*
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.5
Connection: keep-alive
Cookie: csrftoken=......
DNT: 1
Host: 127.0.0.1:3000
Referer: http://127.0.0.1:3000/login
Sec-GPC: 1
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:84.0) Gecko/20100101 Firefox/84.0

我从各种链接尝试了许多解决方案,但都没有奏效。我一遍又一遍地遇到同样的错误。但它正在处理 GET 请求。

请帮忙!

【问题讨论】:

    标签: python django django-rest-framework cors next.js


    【解决方案1】:

    您是否尝试将http://127.0.0.1:8000http://127.0.0.1:3000 添加到CORS_ALLOWED_ORIGINS
    似乎只接受来自http://localhost:3000 的请求。

    【讨论】:

    • 我不知道是怎么做到的,但这次在将http://127.0.0.1:3000 添加到CORS_ALLOWED_ORIGINS 列表后它起作用了!!
    猜你喜欢
    • 2021-12-19
    • 2012-08-08
    • 2020-01-05
    • 2018-03-28
    • 2021-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-10
    相关资源
    最近更新 更多