如何在同构应用程序中通过节点提取传递请求cookie

How to pass Request cookies through node-fetch in isomorphic app?

本文关键字:提取 节点 cookie 请求 同构 应用程序      更新时间:2024-05-04

我正试图使用React、Express和同构获取(基于客户端上的whatwg-fetch和服务器上的node-fetch),从这个常见的样板中构建同构项目。我使用cookie作为我的访问令牌,前端的credentials: 'same-origin'将其发送到GraphQL,效果非常好。

问题是,我不能在服务器端使用相同的解决方案——node-fetch只是不支持从盒子中使用XMLHttpRequest cookie。我的获取请求在路由器的几个抽象层下,所以我不能只使用req中的cookie值。

这是我的server.js代码(完整版):

server.get('*', async (req, res, next) => {
  try {
    // some presettings here..
    await Router.dispatch({ path: req.path, query: req.query, context }, (state, component) => {
      data.body = ReactDOM.renderToString(component);
    });
    res.send(template(data));
  } catch (err) {
    next(err);
  }
});

和Route的index.js(完整版):

export const action = async (state) => {
  const response = await fetch('/graphql?query={me{id,email}}', {
    credentials: 'same-origin',
  });
  const { data } = await response.json();
  // ...
  return <Login title={title} me={data.me} />;
};

如何将令牌从server.js传递到获取模块?或者,也许还有一些更好的决定?

首先,我希望您现在已经找到了答案!

其次,cookie实际上只是标头。如果需要发送cookie来授权服务器端请求,则始终可以创建cookie值所需的字符串,并将其作为标头发送。

举个例子,看看这个服务器端node-fetch包装器是如何将保存的cookie附加到出站请求的:https://github.com/valeriangalliat/fetch-cookie/blob/master/index.js#L17