我正在尝试使用 Django 和 React 进行简单的基于会话的身份验证,但浏览器不会设置 cookie
登录查看:
class LoginView(APIView):
def post(self, request):
username = request.data.get("username")
password = request.data.get("password")
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
return Response(
{"message": "Login successful", "username": user.username},
status=status.HTTP_200_OK,
)
else:
return Response(
{"error": "Invalid credentials"}, status=status.HTTP_401_UNAUTHORIZED
)
前端逻辑:
const getData = () => {
fetch("http://127.0.0.1:8000/me/").then(
(res) => {
return res.json()
}
).then(
(data) => {
setUsername(data.username)
}
)
}
const login = () => {
fetch("http://127.0.0.1:8000/login", {
method: "POST",
body: JSON.stringify({
"username": "user",
"password": "password"
}),
headers: {
"Content-Type": "application/json",
}
}).then(function(response){
return response.json();
}).then((data) => console.log(data));
getData()
}
注意:后端实际上发送回 Set-Cookie 标头:
set-cookie:
csrftoken=OHi2iTT8vDvnn7pAzbb705zrj3gFkFLK; expires=Thu, 15 Jan 2026 08:31:49 GMT; Max-Age=31449600; Path=/
set-cookie:
sessionid=jna0kbgo4k8x8spoyzyyxch2d24bz2li; expires=Thu, 30 Jan 2025 08:31:49 GMT; HttpOnly; Max-Age=1209600; Path=/
fetch(…)
[mdn-doc]的 cookie。您可以使用 credentials: true
[mdn-doc] 作为启用发送 cookie 的选项:
const getData = () => {
fetch("http://127.0.0.1:8000/me/", {credentials: true})
}