reactjs 应对django CORS问题

vc9ivgsu  于 2023-02-22  发布在  React
关注(0)|答案(5)|浏览(138)

错误详细信息

点击按钮时生成两个请求。

到目前为止我搜索了什么

Axios blocked by CORS policy with Django REST Framework
CORS issue with react and django-rest-framework
但无济于事
"我在做什么"
从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',
]

响应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);
    });
}

尝试使用提取的另一种方法,但无效

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);
    });
}

Django侧边法

def Login(request):
    if(request.method == "POST"):
        return JsonResponse({"message" : "Invalid credentials"}, status=401)
anauzrmj

anauzrmj1#

以下设置适合我

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

jrcvhitl2#

尝试删除CORS_ALLOWED_ORIGINS。保留CORS_ORIGIN_ALLOW_ALL = True即可。
这是我在真实的服务器上的设置:

CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = True
CORS_ALLOW_HEADERS = [
  'accept',
  'accept-encoding',
  'authorization',
  'content-type',
  'origin',
  'dnt',
  'user-agent',
  'x-csrftoken',
  'x-requested-with']
CORS_ALLOW_METHODS = ['DELETE', 'GET', 'OPTIONS', 'PATCH', 'POST', 'PUT']
2j4z5cfb

2j4z5cfb3#

如果你想让ReactJS应用程序可以在线访问你的服务器端点,那么你应该尝试在Djangosettings.py文件中设置这个

CORS_ORIGIN_ALLOW_ALL = False

CORS_ALLOW_CREDENTIALS = True

CORS_ALLOWED_ORIGINS = [
    'http://localhost:3000',
    'http://xxx.xxx.xxx.xxx:portNum',
]

CORS_ALLOW_METHODS = [
    'DELETE',
    'GET',
    'PATCH',
    'POST',
    'PUT',
]

# Any headers you wanted to be visible by the ReactJS app.
CORS_EXPOSE_HEADERS = [
    'Date'
]
xiozqbni

xiozqbni4#

有时候会因为url模式而发生这种情况。请检查url模式是否需要在末尾加斜线。
尝试使用'login'而不是'login/'

jmp7cifd

jmp7cifd5#

我想,你忘了提供“风尚”:“cors”来处理您的请求,是吗?而且您必须在服务器端处理浏览器在印前检查阶段发出的“OPTIONS”请求。
“Access-Control-Allow-Origin”标头应该由服务器在响应中发送。请求中不需要它。
在此处阅读有关“CORS”请求的详细说明:https://javascript.info/fetch-crossorigin
要正确设置Django,请阅读以下内容:How can I enable CORS on Django REST Framework

相关问题