(Next.js,Express session)为getInitialProps中的每个请求创建新会话

(Next.js,Express session)为getInitialProps中的每个请求创建新会话,express,express-session,next.js,Express,Express Session,Next.js,我正在尝试使用,并且已经在客户端成功地这样做了,但是从getInitialProps内部进行的API调用遇到了问题 static async getInitialProps(ctx) { const res = await fetch('path/to/endpoint', { headers: { cookie: ctx.req.headers.cookie, }, }); const user = awa

我正在尝试使用,并且已经在客户端成功地这样做了,但是从getInitialProps内部进行的API调用遇到了问题

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

      return { user };
    }
注意:我正在使用进行API调用。我的Next.js安装在localhost:3000上运行,我的Express服务器在localhost:5000上运行

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

我在这里记录res是因为我想看到标题。结果表明该请求有一个空的headers对象。如果我兑现承诺,我会得到我要求的数据。即使刷新页面,此调用的会话ID在服务器上也保持一致。这里一切正常

下面是getInitialProps内部API调用的示例:

componentDidMount() {
  fetch('/path/to/endpoint', {
    method: 'GET',
    credentials: 'include',
  }).then((res) => console.log(res));
}
static async getInitialProps(ctx) {
  fetch('/path/to/endpoint', {
    method: 'GET',
    credentials: 'include',
  }).then((res) => console.log(res.headers));
}
同样,记录日志以查看标题。此响应具有标题,它们如下所示:

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' ] } }
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,
  }),
})
正如您所看到的,在我的set cookie头中有connect.sid(express session ID),但问题是每当我刷新页面时,connect.sid cookie都会更改,并且与客户端API调用的会话ID不匹配(即使刷新页面后仍然保持不变)

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

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' ] } }
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,
  }),
})
))


如果有人知道如何从getInitialProps内部进行API调用,并使用express会话,我将非常感谢您的输入!提前谢谢。

我找到了解决方案。我没有使用
凭据:“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 };
    }

非常感谢。为什么默认情况下不发送cookie?!据我所知,CORS是服务器和浏览器之间的契约。由于getInitialProps仅在服务器端渲染期间运行,而不在客户端渲染期间运行,因此它不知道CORS,因此无法解释
凭据:“include”
。也许阅读文档可以帮助您更好地理解它:至于为什么默认情况下不发送cookie,我想答案只是Next.js没有默认发送cookie的实现。“getInitialProps也将在客户端运行。如果你有只想在服务器上运行的代码,你可以检查process.browser,它只会在客户端上运行。”-从spectrum nextjs Community的聊天中复制这听起来与我的问题非常相似:请注意,这对axios不太好。一旦我切换到同构提取,它就开始工作了。