Django, Next.JS: CORS头' Access-Control-Allow-Origin '丢失,即使定义



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

My Django settings:

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

My Next.js page:

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 header:

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

我从不同的链接尝试了许多解决方案,但都不起作用。我一次又一次地得到同样的错误。

请帮忙!

您是否尝试过将http://127.0.0.1:8000http://127.0.0.1:3000添加到CORS_ALLOWED_ORIGINS中?
似乎只有http://localhost:3000的请求才会被接受。

最新更新