gpt4 book ai didi

node.js - Cookie session 未存储在React中

转载 作者:太空宇宙 更新时间:2023-11-03 22:58:13 26 4
gpt4 key购买 nike

我之前用客户端渲染制作了一个全栈应用程序,但是由于某种原因,我的应用程序在发出get请求时给出了req.user的未定义。

我会解释并尝试尽可能详尽

首先,我正在从客户端(http://localhost:3000)请求

axios.get("http://localhost:8080/auth/google").then(response 


这是我的回调URL( http://localhost:8080

router.get("/google/callback", passport.authenticate('google'), (req, res) => {
res.redirect(http://localhost:3000/home)
})


有了这个,我期待我的应用程序存储 localhost:3000的cookie,即无论何时何地我请求路由中间件isLoggedIn的地方时,我都应该能够从客户端( http://localhost:3000/)访问该路由,即

向我的客户提出要求

axios.get("http://localhost:8080/home").then(response 


到路线( http://localhost:8080

router.get("/home", MiddlewareAuth.UserLoggedIn, (req, res) => {
res.send(req.user)
})


应该给/返回req.user而不是返回未定义(实际上抛出错误,因为在我的中间件中,如果用户未登录,我正在设置res.status(401)。

现在,如果我手动转到 http://localhost:8080/home,则可以看到 req.user作为响应(从 http://localhost:3000http://localhost:8080/home发出请求时看不到)。

我怀疑我的Cookie没有存储在localhost:3000 /

这就是我初始化会议的方式

app.use(cors({
'allowedHeaders': ['sessionId', 'Content-Type'],
'exposedHeaders': ['sessionId'],
'credentials': true,
'origin': ['http://localhost:3000', 'http://192.168.0.86:3000'],
}))

//Storing cookies on the client side
app.use(cookieSession({
keys: ["abbcbba2"],
maxAge: 24 * 60 * 60 * 1000
}))


app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: true}))



//Passport intialize
app.use(passport.initialize());
app.use(passport.session());


有人可以帮我发现问题吗

最佳答案

您在axios请求中缺少withCredentials: true

尝试这个

axios.get("http://localhost:8080/home", {withCredentials: true}).then(response 


它可能应该工作。

关于node.js - Cookie session 未存储在React中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54183889/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com