首页 > 解决方案 > 为什么 Postman 在我的 React 应用程序中接收到 express session cookie 但没有接收到我的 post 请求

问题描述

我有一个带有 express、express-session 和护照的 nodejs 服务器进行身份验证。我的登录路线如下所示:

router.post('/login', passport.authenticate('local'), (req, res) => {
  return res.status(200).json({
    message: "Auth successful",
    username: req.user.username
  })
})

当我使用 Postman 测试路由时,我在响应中收到带有会话 ID 的 cookie:Postman 结果但是当我在 React 中使用 axios 进行发布请求时,我没有收到任何 cookie:

const login = (email, password) => {
    const reqBody = {
        email,
        password
    }

    const config = {
        withCredentials : true,
    }

    return axios.post(`${serverUrl}/user/login`, reqBody, config)
}

这是我的 Node.js 服务器中的 cors:

// Cors definition 
app.use((req, res, next) => {
  res.setHeader('Access-Control-Allow-Origin', 'http://localhost:3000')
  res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept')
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE')
  res.setHeader('Access-Control-Allow-Credentials', true)

  next()
})

Chrome 上的网络选项卡正如您所见,控制台中没有 cookie 选项卡,并且在标题中注明。所以我想知道为什么以及如何解决这个问题。

标签: node.jsreactjspassport.jspostmanexpress-session

解决方案


所以!我有点找到了为什么我可以在 Postman 响应中看到 cookie 而不是我的浏览器(Chrome)的答案。我在 chrome 中找到了 cookie,而不是在页面控制台中的application -> Storage -> Cookies中,而是在chrome://settings/cookies/detail?site=192.168.2.89中。

我的理解是 express-session 或 postman.session() 仅在 cookie 上设置 http:

在生成 cookie 时使用 HttpOnly 标志有助于降低客户端脚本访问受保护 cookie 的风险(如果浏览器支持它)。https://www.owasp.org/index.php/HttpOnly

我仍然无法看到 express 在哪里设置标头以及如何记录服务器发送的 cookie。


推荐阅读