问题描述
我不断看到有关在Apollo Client上设置上下文的示例,例如:
new ApolloClient({
uri: '...',request(operation) {
const currentUser = readStore<CurrentUser>("currentUser");
currentUser &&
operation.setContext({
headers: { authorization: currentUser.token },other: "things"
});
}
});
}
带有转到请求标头的内容和“其他”内容。然而,经过2个多小时的研究,我找不到在Apollo Server的另一端检索其他上下文数据的示例。
似乎所有示例都与授权令牌有关,但是如何检索其余内容,例如使用apollo-server-express
?
这是我到目前为止所拥有的:
const apollo = new ApolloServer({
typeDefs,resolvers,context({ req }): Context {
const currentUser =
(req.headers.authorization &&
(jwt.verify(
req.headers.authorization,process.env.JWTSIGN
) as Context["currentUser"])) ||
null;
// Ok for req.headers.authorization,how to I get "other: things" ?
return {
ip: req.ip,currentUser
};
}
});
此处的context
函数仅从Express获取一个req和一个res对象。经过一些日志后,似乎没有包含我想要的数据。
谢谢。
解决方法
在您共享的示例中共享标题的唯一原因是,ApolloClient
在其上下文中使用headers
值填充了发出请求时发送的HTTP headers。然后,这些标头由express
解析,并在req
对象上可用。 ApolloClient
使用的上下文严格是客户端的。 ApolloServer
使用的上下文严格是服务器端的。您不能使用ApolloClient
的上下文将任意值传递到服务器-您应该在GraphQL查询中使用标头或参数。