node.js - 无法从 Heroku 上托管的 Express 应用程序设置 cookie

标签 node.js express heroku cookies setcookie

我在 Heroku 中托管了前端和后端。

  • 前端 - xxxxxx.herokuapp.com( react 应用程序)
  • 后端 - yyyyyy.herokuapp.com (express)

  • 我正在尝试实现 Google 身份验证。从 Google OAuth2 获取 token 后,我尝试设置 id_token以及通过 express 应用程序在 cookie 中的用户详细信息。

    下面是我在后端的一段代码,
    authRouter.get('/token', async (req, res) => {
        try {
            const result = await getToken(String(req.query.code))
            const { id_token, userId, name, exp } = result;
            const cookieConfig = { domain: '.herokuapp.com', expires: new Date(exp * 1000), secure: true }
            res.status(201)
                .cookie('auth_token', id_token, {
                    httpOnly: true,
                    ...cookieConfig
    
                })
                .cookie('user_id', userId, cookieConfig)
                .cookie('user_name', name, cookieConfig)
                .send("Login succeeded")
        } catch (err) {
            res.status(401).send("Login failed");
        }
    });
    

    它在我的本地非常适合我,但它不适用于 heroku。

    这些是我已经尝试过的域 - .herokuapp.com herokuapp.com .另外,我在没有指定域字段本身的情况下进行了尝试。

    我可以看到 Set-Cookie响应 header 的详细信息,但/token 端点失败而没有返回任何状态代码,我看不到应用程序选项卡上设置的 cookie。

    请看下面的图片,

    enter image description here
    我在这里看不到任何状态代码,但它说它失败了。
    I can't see any status code here
    这些是我可以看到的 cookie 信息,但如果我通过应用程序选项卡检查,则不可用。
    enter image description here

    我在这里错过了什么?有人可以帮助我吗?

    最佳答案

    可能你应该尝试安全:secure: req.secure || req.headers['x-forwarded-proto'] === 'https'

    关于node.js - 无法从 Heroku 上托管的 Express 应用程序设置 cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62106113/

    相关文章:

    javascript - 在 Meteor 中使用自动表单将 postId 添加到评论中

    javascript - 未找到该相关模块:

    c# - 使 ASP.NET 身份在 Mongo 中存储用户数据(托管在 Heroku 上)

    Grails 3 和 Heroku - 找不到阶段任务

    ruby-on-rails - 如何将两个 Rails 应用程序数据库和模型链接在一起?

    javascript - VueJs 2、NodeJs 和重新加载页面

    node.js - MongoDB 查询返回错误结果

    node.js - 使用 NodeJs 异步查询 redshift 集群

    javascript - 页面刷新清除所有数据

    javascript - Node.js 使用 Express 和 EJS 更新 View 中的单个元素