【问题标题】:How to save cookie on development localhost如何在开发本地主机上保存 cookie
【发布时间】:2020-11-14 20:24:59
【问题描述】:

我的 node.js 带有带有一些端点的 express 后端,使用 curl 或 postman 进行的所有测试都可以正常工作,但是在我的客户端,在 http.post 请求上使用 angular 时,我得到了正确的响应,但没有保存任何 cookie。 我尝试更改我的 localhost dns,经过一番尝试后,我最终使用了 127.0.0.1:4200 客户端和 127.0.0.1:3000 后端。

后端代码:

const express = require('express');
const bodyParser = require('body-parser');
const webpush = require('web-push');
const cors = require('cors');
const cookieParser = require('cookie-parser');

const app = express();
app.use(cors());
app.use(bodyParser.json());
app.use(cookieParser());

app.post(path, /*here I call my function*/);
[...]
/*in my function i set cookie with these lines*/
res.cookie('userData',
   {token: token,},{ httpOnly: true, secure: false }
);

客户端代码:

[...]
constructor(private http: HttpClient) {}
[...]
/*request on my button click*/
this.http
      .post<AuthResponse>(path, bodyReq)

谁关心这些代码,让我们看看结果。

在响应头中我可以看到 set-cookie,当我切换到请求的 cookie 选项卡时,我可以正确看到它,但是..

有些东西告诉 chrome 不要保存我的 cookie,他收到了!! 我已经在网上查看了有关 cors、域、cookie 设置的信息。 没有什么对我有用。 感谢您的帮助。

【问题讨论】:

  • 我已经试过了,在客户端请求时手动设置 withCredentials true 时会阻止它
  • 是的,看看下面的答案,它在谈论 cors

标签: express cookies browser http-post


【解决方案1】:

BENARD Patrick 的建议是对的!!

要解决我的问题,在客户端和服务器上都添加 withCredentials(使用此解决方案我必须指定域)

客户端代码:

return this.http
      .get<AuthResponse>(path, {
        withCredentials: true,
        headers: new HttpHeaders({
          'Content-Type': 'application/json',
          'Access-Control-Allow-Origin': 'www.dns_to_127.0.0.1.com:4200',
        }),
      })

服务器代码:

app.use(
  cors({
    origin: 'http://www.dns_to_127.0.0.1.com:4200',
    credentials: true,
  })
);

credentials:配置 Access-Control-Allow-Credentials CORS 标头。设置为 true 以传递标头

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-03-13
    • 2012-01-22
    • 2019-08-20
    • 2019-10-31
    • 1970-01-01
    • 2019-12-12
    • 2014-01-04
    • 1970-01-01
    相关资源
    最近更新 更多