我正试图使用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