0

我正在使用 MERN 堆栈并已实现服务器端社交登录。作为用户,我可以让用户使用 Google 登录。用户登录后,我将尝试检查用户是否从前端(React)登录。

服务器.js

app.get("/auth/google",
  passport.authenticate("google", { scope: [ 'email', 'profile' ] })
);
app.get("/auth/google/callback",
  passport.authenticate("google", { failureRedirect: "http://localhost:3000" }),
  function(req, res) {
    // Successful authentication, redirect secrets.
    res.redirect("http://localhost:3000");
  });

app.get("/logout", function(req, res){
  req.session.destroy(function(e){
    req.logout();
    res.redirect("http://localhost:3000/");
  });
});

Users.js(后端)

router.route('/isLoggedIn').get((req, res) => {
    console.log(req.user); //undefined
  if (req.user) {
    res.send(true);
  } else {
    res.send(false);
  }
});

App.js(客户端)

useEffect(() => {
    axios.get(`${process.env.REACT_APP_SERVER_URL}/users/isLoggedIn`)
    .then(function (response) {
        // handle success
        console.log(response);
    });
    
  });

如果我尝试在浏览器中检查端点http://localhost:8000/users/isLoggedIn,我会在用户登录后得到响应 true。但是在发出 get 请求时,req.user返回undefined. 有没有其他方法可以检查用户是否登录?

4

0 回答 0