(Next.js,Express session)getInitialProps中发出的每个请求的新会话

Rob*_*ert 3 express express-session next.js

我试图使Express会话Next.js一起工作,并且已在客户端成功完成,但我在使用getInitialProps内部进行的API调用时遇到问题.

注意:我使用isomorphic-unfetch进行API调用.我的Next.js安装在localhost:3000上运行,我的Express服务器在localhost:5000上运行.

以下是客户端API调用的示例(在getInitialProps之外):

componentDidMount() {
  fetch('/path/to/endpoint', {
    method: 'GET',
    credentials: 'include',
  }).then((res) => console.log(res));
}
Run Code Online (Sandbox Code Playgroud)

我在这里记录res是因为我想查看标题.原来这个请求有一个空头标题对象.如果我解决了这个承诺,我会得到我要求的数据.即使我刷新页面,此调用的会话ID在服务器上也保持一致.一切都在这里按预期工作.

以下是getInitialProps中API调用的示例:

static async getInitialProps(ctx) {
  fetch('/path/to/endpoint', {
    method: 'GET',
    credentials: 'include',
  }).then((res) => console.log(res.headers));
}
Run Code Online (Sandbox Code Playgroud)

再次,记录以查看标题.这个响应有标题,它们看起来像这样:

Headers {
_headers:
{ 'x-powered-by': [ 'Express' ],
'access-control-allow-origin': [ 'http://localhost:3000' ],
vary: [ 'Origin, Accept-Encoding' ],
'access-control-allow-credentials': [ 'true' ],
'x-frame-options': [ 'SAMEORIGIN' ],
'x-xss-protection': [ '1; mode=block' ],
'set-cookie'['YgJGcZPBgbE_nEqqLZpw0ba0pyaf2eNS','connect.sid=s%3AYgJGcZPBgbE_nEqqLZpw0ba0pyaf2eNS.Oye%2F7%2BsyXrrLJwphEJ3nq3yMkBhM3%2Fm4PCl9KIV%2FTzA; Path=/; Expires=Sun, 05 Aug 2018 15:56:52 GMT;     HttpOnly' ],
'content-type': [ 'application/json; charset=utf-8' ],
'content-length': [ '246' ],
etag: [ 'W/"f6-82FKQ+ERtkxLiKa8hEIeY4kgGgE"' ],
date: [ 'Sun, 22 Jul 2018 15:56:52 GMT' ],
connection: [ 'close' ] } }
Run Code Online (Sandbox Code Playgroud)

正如你可以看到有connect.sid我set-cookie头(Express会话ID),但问题是,每当我刷新页面不匹配的客户端API调用的会话ID(在connect.sid饼干变化即使刷新页面后也保持不变).

Express服务器上的会话对象如下所示:

app.use(
  session({
  resave: false,
  name: 'connect.sid',
  saveUninitialized: false,
  secret: SESSION_SECRET,
  unset: 'destroy',
  cookie: {
    maxAge: 3600000 * 24 * 14,
    secure: false,
  },
  store: new MongoStore({
    url: mongoUrl,
    autoReconnect: true,
  }),
})
Run Code Online (Sandbox Code Playgroud)

);

如果有人知道如何从getInitialProps内部进行API调用与快速会话一起工作,我会很感激输入!先感谢您.

Rob*_*ert 7

我找到了解决方案.而不是使用credentials: 'include'我必须在请求标头中发送会话cookie.这是getInitialProps中的工作请求.

static async getInitialProps(ctx) {
      const res = await fetch('path/to/endpoint', {
        headers: {
          cookie: ctx.req.headers.cookie,
        },
      });
      const user = await res.json();

      return { user };
    }
Run Code Online (Sandbox Code Playgroud)