小编Rob*_*ert的帖子

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

我试图使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': [ …
Run Code Online (Sandbox Code Playgroud)

express express-session next.js

3
推荐指数
1
解决办法
1234
查看次数

标签 统计

express ×1

express-session ×1

next.js ×1