错误详情
单击按钮时生成了两个请求。
到目前为止我搜索了什么?
Axios 通过 Django REST Framework 被 CORS 策略阻止 https://stackoverflow.com/questions/55366740/axios-blocked-by-cors-policy-with-django-rest-framework
React 和 django-rest-framework 的 CORS 问题 https://stackoverflow.com/questions/61444853/cors-issue-with-react-and-django-rest-framework?rq=1
但无济于事
我在做什么?
从 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)