【问题标题】:How can I set the domain attribute in express-session based on the request origin?如何根据请求来源在 express-session 中设置域属性?
【发布时间】:2021-07-02 16:08:20
【问题描述】:

我正在使用快速会话。我设置了域 domain: 'mydomain.com',以便可以在子域之间设置会话 cookie,例如 api.mydomain.comstaging.mydomain.com

但这会阻止Set-Cookie 标头在使用 localhost 前端进行测试时设置 cookie。我得到Set-Cookie was blocked because its Domain attribute was invalid with regards to the current host url.

所以如果源是本地主机,我需要将域属性更改为本地主机。

如果我有条件地设置域,我们无权访问req

  app.use(session({
      secret: 'very secret 12345', 
      resave: true,
      saveUninitialized: false,
      store: new MongoStore({ mongooseConnection: mongoose.connection }),
      cookie: {
        domain:
          req.get('origin').slice(0, 17) === 'http://localhost:' ? 'localhost' : 'mydomain.com',
        secure: true,
        httpOnly: true,
        sameSite:  none,
      },
    })
  );

这将返回ReferenceError: req is not defined

所以我尝试在自定义中间件中调用session 以访问req

  app.use((req, res, next) =>
        session({
      secret: 'very secret 12345',
      resave: true,
      saveUninitialized: false,
      store: new MongoStore({ mongooseConnection: mongoose.connection }),
      cookie: {
        domain:
          req.get('origin').slice(0, 17) === 'http://localhost:' ? 'localhost' : 'mydomain.com',
        secure: true,
        httpOnly: true,
        sameSite:  none,
      },
    })
  );

但它不起作用。似乎有了这个,resreqnext 不会被传递给 session() 返回的中间件函数。我也尝试调用返回 -session({..options..})() 的函数 session() ,但这也不起作用。

如何根据请求来源设置域属性?

【问题讨论】:

    标签: node.js express cors express-session


    【解决方案1】:

    我必须调用函数并传入reqresnext

      app.use((req, res, next) =>
        session({
          secret: 'very secret 12345', // to do, make environment variable for production
          resave: true,
          saveUninitialized: false,
          store: new MongoStore({ mongooseConnection: mongoose.connection }),
          cookie: {
            domain:
              req.get('origin').slice(0, 17) === 'http://localhost:' ? 'localhost' : 'mydomain.com',
            secure: true,
            httpOnly: true,
            sameSite:  none,
          },
          },
        })(req, res, next)
      );
    

    【讨论】:

    • @vodolaz095 第二种方式怎么可能? Req 是未定义的?
    • 原来的答案是对的。编辑不正确。这个问题和答案不应该被否决。请仔细阅读问题
    • req 是正确的,expressjs 有两种类型的中间件-错误处理程序一种-function(error, req,res,next).... 和普通的一种function(req,res,next)...。会话是第二种类型,普通的一种
    • 不正确。 req 未定义。试试吧。它给你ReferenceError: req is not defined。想想看。 session 函数不是运行的中间件。 session 返回的函数是中间件。所以req.get('origin')运行时req还没有传入。
    猜你喜欢
    • 2019-03-16
    • 2021-12-17
    • 2019-10-21
    • 2016-08-01
    • 2021-08-10
    • 2012-11-18
    • 2020-11-24
    • 2021-11-09
    • 1970-01-01
    相关资源
    最近更新 更多