代码之家  ›  专栏  ›  技术社区  ›  Shan Robertson

无法从节点服务器->应用设置cookie

  •  0
  • Shan Robertson  · 技术社区  · 3 年前

    我正在尝试从我的节点设置httpOnly cookie。js api(localhost:3001)与我的react客户端应用程序(localhost:3000)配合使用时,我迄今为止尝试的所有方法都不会在浏览器中设置cookie。有关我的设置的一些关键因素:

    后端是节点,运行Fastfy、Fastfy cookie&科尔斯

    // 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 在服务器上总是返回一个空白对象 {} .有什么建议吗?

    0 回复  |  直到 3 年前
        1
  •  0
  •   Nishant S Vispute    3 年前

    你所面临的是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=value 一双 访问控制允许源 在您的回复和请求中,域名应该匹配,否则浏览器上不会设置cookie。。。

    这里有一个GitHub问题 Link 同样的问题