【发布时间】:2021-12-05 05:43:01
【问题描述】:
错误详情
点击按钮时产生了两个请求。
到目前为止我搜索了什么?
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);
});
}
尝试了另一种使用 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);
});
}
DJango侧法
def Login(request):
if(request.method == "POST"):
return JsonResponse({"message" : "Invalid credentials"}, status=401)
【问题讨论】:
-
尝试在设置文件中添加 CORS_ALLOW_CREDENTIALS = False
-
尝试将 cors 中间件添加到您的中间件数组的第一个位置并给我反馈,谢谢
-
如果其他所有内容都被注释掉,
CORS_ORIGIN_ALLOW_ALL=True会做任何事情吗? -
没有发生任何变化。同样的错误。如果您需要更多信息,请告诉我。
标签: python reactjs django python-3.9