【发布时间】:2020-08-23 11:36:03
【问题描述】:
我的前端和后端是分离的,客户端在localhost:3000 上运行,后端在localhost:8000 上运行。我有 csrf 和刷新令牌,我将它们设置为服务器端的 cookie。现在我需要客户端的那些 cookie。
这是我写的反应代码:
fetch('http://localhost:8000/api/Acutes/SignIn/', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'withCredentials': 'true'
},
body: JSON.stringify(values)
})
.then(data => data.json())
.then(data =>{
console.log(data)
})
.catch(error =>{
console.error(error);
})
Django 设置
CORS_ORIGIN_WHITELIST = [
"http://localhost:9001",
"http://localhost:3000"
]
CORS_ALLOW_HEADERS = [
'accept',
'accept-encoding',
'authorization',
'content-type',
'dnt',
'origin',
'user-agent',
'x-csrftoken',
'x-requested-with',
'withCredentials'
]
使用它时似乎出现的错误如下。
Access to fetch at 'http://localhost:8000/api/Acutes/SignIn/' from origin 'http://localhost:3000' has been blocked by CORS policy: Request header field withcredentials is not allowed by Access-Control-Allow-Headers in preflight response.
我应该如何处理这个错误并将我的cookies放到客户端?TIA
【问题讨论】:
-
你需要更新它的后端
-
@ShubhamVerma 我在后端添加了“withCredentials”,但只有 csrf 令牌在 cookie 中可用,即使没有任何令牌是 HTTPonly
-
它的 cors 问题。我对django一无所知。基本上你需要允许本地主机或不同的端口。它不是前端问题
-
你检查过这个问题吗? stackoverflow.com/questions/32500073/…您可以尝试删除 withCredentials 标头字段以查看是否允许基本请求。
-
用
CORS_ORIGIN_ALLOW_ALL = True替换CORS_ORIGIN_WHITELIST = [...]并让我们知道行为。谢谢。
标签: django reactjs cookies decoupling csrf-token