【问题标题】:Unable to set cookie from node server -> app无法从节点服务器设置 cookie -> 应用程序
【发布时间】:2021-07-30 04:48:51
【问题描述】:

我正在尝试从我的 node.js api (localhost:3001) 设置一个 httpOnly cookie 以与我的 react 客户端应用程序 (localhost:3000) 一起使用,到目前为止我所做的一切都导致没有设置任何 cookie我的浏览器。关于我的设置的一些关键因素:

后端是node,运行fastify,fastify-cookie & cors

// CORS
server.use(
    require('cors')({
        origin: ['https://localhost:3000'],
        optionsSuccessStatus: 200,
        credentials: true
    })
)

// Cookies
server.register(require('fastify-cookie'), {
    secret: process.env.JWT_SECRET
})

// Sending the cookie
reply
  .setCookie('token', token, {
    domain: 'localhost',
    path: '/',
    secure: true,
    sameSite: 'lax',
    httpOnly: true
})
.send({ user })

客户端在chrome中运行https localhost,使用fetch进行api调用。

const fetchUsers = async () => {
    const req = await fetch(`${process.env.USERS_API_BASE}/users`, { credentials: 'include' })
    const res = await req.json()
    console.log(res)
}

结果

在我的 chrome 应用程序检查器中没有设置任何 cookie,但它从服务器发送到浏览器并且看起来正确。

set-cookie: token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOjEsImVtYWlsIjoiaGVsbG9Ac2hhbi5kaWdpdGFsIiwiaWF0IjoxNjIwNDI1ODI0LCJleHAiOjE2MjA0Mjk0MjR9.S8eOQMtSBY85wlenuxjIGYNuk3Ec5cKQ87pAhmCvQ9w.nfRxGzq3IMFimC%2FSJeUH9Xl7bH%2FyXVprwK1NBYfur4k; Domain=localhost; Path=/; HttpOnly; Secure; SameSite=Lax

服务器上的request.cookies 总是返回一个空白对象{}。有什么建议吗?

【问题讨论】:

    标签: node.js cookies fetch


    【解决方案1】:

    您面临的是一个 CORS 错误,或者至少它被归类为一个.. 您看到服务器似乎认为您正在发出跨域请求..

    如果您记录 响应标头,这通常是您会看到的

    HTTP/1.1 200 OK
    Date: Sun, 20 May 2018 20:43:05 GMT
    Server: Apache
    Set-Cookie: name=value; expires=Sun, 20-May-2018 21:43:05 GMT; Max-Age=3600; path=/; domain=.localHost
    Cache-Control: no-cache, private
    Access-Control-Allow-Origin: http://localHost:8080
    Vary: Origin
    X-RateLimit-Limit: 60
    X-RateLimit-Remaining: 59
    Content-Length: 2
    Keep-Alive: timeout=10, max=100
    Connection: Keep-Alive
    Content-Type: text/html; charset=UTF-8
    

    但是当你提出请求时,你有点像这样发送它

    const res = await axios({ method: 'POST', url: 'http://127.0.0.1:3000/api/v1/users/login', data: { email, password } });
    

    您是否看到问题 127.0.0.1 != http://localhost:8000,这就是您问题的解决方案

    简而言之,检查您的响应中的Key=valueAccess-Control-Allow-Origin 并请求域名应该匹配,否则不会在浏览器上设置cookie...

    这是一个 GitHub 问题 Link 解决同样的问题

    【讨论】:

    • 我明白你在说什么,但我没有使用127.0.0.1 来引用任何内容。在发送 cookie 的请求的响应中,我确实看到了 Remote Address: 127.0.0.1:3001,但这是我能看到的 IP 版本的唯一参考。
    • 在这种情况下,在您创建和发送 cookie 的服务器上,您需要将其更改为 \`http://locahost:${PORT}`\
    猜你喜欢
    • 2016-01-09
    • 1970-01-01
    • 2019-01-30
    • 1970-01-01
    • 2019-05-12
    • 2019-08-06
    • 1970-01-01
    • 2017-07-31
    • 1970-01-01
    相关资源
    最近更新 更多