错误详情
单击按钮时生成了两个请求。
到目前为止我搜索了什么?
Axios blocked by CORS policy with Django REST Framework
CORS issue with react and django-rest-framework
但无济于事
我在做什么?
将 POST 请求从 react 提交到 DJango API
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_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',
]
关于python - 对 Django CORS 问题使用react,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69611485/