错误详细信息
点击按钮时生成两个请求。
到目前为止我搜索了什么
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)
5条答案
按热度按时间anauzrmj1#
以下设置适合我
jrcvhitl2#
尝试删除
CORS_ALLOWED_ORIGINS
。保留CORS_ORIGIN_ALLOW_ALL = True
即可。这是我在真实的服务器上的设置:
2j4z5cfb3#
如果你想让ReactJS应用程序可以在线访问你的服务器端点,那么你应该尝试在Django
settings.py
文件中设置这个xiozqbni4#
有时候会因为url模式而发生这种情况。请检查url模式是否需要在末尾加斜线。
尝试使用
'login'
而不是'login/'
jmp7cifd5#
我想,你忘了提供“风尚”:“cors”来处理您的请求,是吗?而且您必须在服务器端处理浏览器在印前检查阶段发出的“OPTIONS”请求。
“Access-Control-Allow-Origin”标头应该由服务器在响应中发送。请求中不需要它。
在此处阅读有关“CORS”请求的详细说明:https://javascript.info/fetch-crossorigin
要正确设置Django,请阅读以下内容:How can I enable CORS on Django REST Framework