我正在尝试使用 React、Express 和同构提取(基于客户端上的 whatwg-fetch
和服务器上的 node-fetch
)从 this 构建同构项目通用样板。我正在为我的访问 token 使用 cookie,并且 credentials: 'same-origin'
在前端 to send it 到 GraphQL - 工作得很好。
问题是我不能在服务器端使用相同的解决方案——node-fetch
只是不支持使用 XMLHttpRequest cookies。我的获取请求在路由器的几个抽象层下,所以我不能只使用 req
中的 cookie 值。
这是我的 server.js
代码 ( full version ):
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);
}
});
和路由的 index.js
( full version ):
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} />;
};
如何将我的 token 从 server.js 传递到我的获取模块?或者,也许有一些更好的决定?
最佳答案
首先,我希望你现在已经找到答案了!
其次,cookie 实际上只是 header 。如果您需要发送 cookie 来授权服务器端请求,您始终可以只创建 cookie 值所需的字符串并将其作为 header 发送。
举个例子,看看这个服务器端 node-fetch
包装器如何将保存的 cookie 附加到出站请求:https://github.com/valeriangalliat/fetch-cookie/blob/master/index.js#L17
关于javascript - 如何在同构应用程序中通过 Node 获取传递请求 cookie?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36536114/