【问题标题】:Why is nodeJS returning different 'req.session'?为什么nodeJS返回不同的'req.session'?
【发布时间】:2021-01-19 16:59:04
【问题描述】:

我正在尝试验证使用 Google API 登录的用户是否已成功登录。在我的 React App 中,我获取到 'http://localhost :3001/auth/google/check' 获取此路径。

我的 React 应用程序中的 fetch:

fetch('http://localhost:3001/auth/google/check', {
        method: 'GET',
        headers: {'Content-Type' : 'application/json'}
    })
    .then(response => response.json())
    .then(data => {
        console.log(data)
        if(data === 'LOGIN_SUCCESS') {    
            const {login, changePage} = this.props;
            login('LOGIN_SUCCESS');
            changePage('GO_TO_PROFILE_PAGE');
        }
    })

在我的服务器中,我正在使用 passportJS 进行身份验证:

app.get('/auth/google/check', (req, res) => {
    console.log(req.session);
    if(req.isAuthenticated()) {
        res.status(200).json('LOGIN_SUCCESS');
    }
    else {
        res.status(400).json('Login failed.');
    }
})

在我的应用页面('http://localhost:3000')上,当我获取时,我收到状态 400,'登录失败'消息,并且在服务器端 'req.session.passport' 未定义,但是,当我打开一个新选项卡并输入 url 'http://localhost:3001/auth/google/check' 时,它返回 'LOGIN_SUCCESS' 并且在我的服务器端我有 'req. session.passport.user' 成功序列化。为什么我收到不同的 'req.session'?

【问题讨论】:

    标签: node.js reactjs express google-api passport.js


    【解决方案1】:

    您可能需要配置 fetch 以在请求中传递 cookie。

    fetch('http://localhost:3001/auth/google/check', {
            method: 'GET',
            headers: {'Content-Type' : 'application/json'},
            credentials: 'include'
        })
    

    参考:https://github.com/github/fetch#sending-cookies

    【讨论】:

      猜你喜欢
      • 2019-12-26
      • 2020-07-31
      • 2014-02-10
      • 2013-05-09
      • 1970-01-01
      • 2013-03-20
      • 2020-10-27
      • 2012-07-28
      • 2013-03-10
      相关资源
      最近更新 更多