【问题标题】:Cookies are not being set in productionCookie 未在生产中设置
【发布时间】:2022-01-18 04:04:11
【问题描述】:

我为 heroku 和 next.js 应用部署了一个 express 服务器。 cookie 是从服务器发送的,甚至显示在网络选项卡中:

但是,cookies 并没有实际存储,我所有的请求都失败了,因为它们依赖于 csrf cookie,并且存储选项卡是空的:

这是在后台设置cookies的代码:

const csrfProtection = csrf({
  cookie: {
    httpOnly: true,
    sameSite: 'none',
    secure: true,
  },
});

app.set('trust proxy', 1);

app.use(cors({ credentials: true, origin: clientOrigin }));

app.get('/', csrfProtection, function (req: Request, res: Response) {
  res.cookie('XSRF-TOKEN', req.csrfToken(), { sameSite: 'none', secure: true });
  res.end();
});

app.use(csrfProtection);

这是我的 axios 实例:

const baseURL = process.env.baseURL;

const axiosInstance = Axios.create({
  baseURL,
  withCredentials: true,
});

和请求代码:

 useEffect(() => {
    dispatch(loadingAction.setToTrue());
    const getCsrf = async () => {
      await axiosInstance.get('/');
    };
    getCsrf()
      .then(() => {
        dispatch(loadingAction.setToFalse());
      })
      .catch((err) => {
        dispatch(loadingAction.setToFalse());
        setError(err);
      });
  }, []);

【问题讨论】:

    标签: node.js reactjs heroku cookies next.js


    【解决方案1】:

    在查看您的屏幕截图时 - 我观察到浏览器具有不同的域集 hilife01 与 hilife-1

    通过 https://hlife01.herokuapp.com/auth/login 访问 - 获取 cookie,但您的应用没有配置正确的路由。

    很可能,正确的域与正在设置的 cookie 没有关联,因此在设置 cookie 时,浏览器会默默地拒绝 cookie,因为您不匹配域,但它在地址栏中可见。

    【讨论】:

    • 那你建议我怎么做?提前致谢。
    • 这取决于您喜欢哪个域,如果 hilife01.herokuap... 很好,然后修复该应用程序的 nodejs 路由 - 如果您希望它保持 hilife-1.herokuapp.com然后找到设置cookie域的代码错误。
    • 再次感谢您的帮助。我真的很感激,但我仍然没有完全理解。 hilife01.herokuap 很好。你在nodejs路由中是什么意思?
    • 是的 - 当你访问你得到的 url _ 不能 GET /auth/login_
    • 您能否更详细地解释一下我的下一步应该是什么?
    猜你喜欢
    • 2018-02-14
    • 2019-05-18
    • 2017-02-17
    • 2021-06-21
    • 1970-01-01
    • 2020-06-28
    • 1970-01-01
    • 2018-12-11
    • 2020-12-31
    相关资源
    最近更新 更多