【问题标题】:How to send cookies to socket.io client from server?如何从服务器向 socket.io 客户端发送 cookie?
【发布时间】:2019-04-23 11:01:25
【问题描述】:

在我的客户上,我这样做:

  useEffect(() => {
    socket.emit('login', myLoginCode)
  }, [])

在服务器端我之前是这样做的:

app.get('login', (req, res) => {
      const cookieProtected = {
        maxAge: 946080000000,
        httpOnly: true,
        secure: true,
        sameSite: true
      } 
      res.cookie('id', login, cookieProtected)
      res.cookie('session', encryptSession, cookieProtected)
      res.cookie('logged', 'true', {
        maxAge: 946080000000,
        secure: true,
        sameSite: true
      })
})

但是我怎样才能对套接字做同样的事情呢?

  socket.on('login', loginCode => {
     // How to to place cookies in user browser from here?
    }

也许有办法用 socket.emit 发送标头?

【问题讨论】:

  • io.on('connection', async socket => { try { socket.handshake.headers.cookie = 'test=1; expires=Fri, 31 Dec 9999 23:59:59 GMT; path=/' 是的,它不起作用。

标签: reactjs express socket.io


【解决方案1】:

如果不重写 IO 库,我们就无法做到这一点,所以唯一的选择是在客户端设置 cookie。

现在我只是在服务器上验证用户并像对象一样发送客户端cookie,然后在客户端我这样做:

document.cookie =
    'id=' +
    loginData.id +
    '; expires=Fri, 31 Dec 9999 23:59:59 GMT; secure; samesite=strict; path=/'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-09-09
    • 2016-09-16
    • 2018-06-03
    • 1970-01-01
    • 1970-01-01
    • 2018-10-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多