Apollo resetStore在Angular客户端中不工作
问题描述:
我正在尝试在客户端集成授权令牌。我将这个令牌传递给中间件。当用户注销重置商店,然后得到一个新的令牌。现在,当我发出新的请求,它仍然是发送旧令牌(缓存)Apollo resetStore在Angular客户端中不工作
这里是我的代码app.module.ts
const networkInterface = createNetworkInterface({
uri: "http://localhost:3000/graphql"
});
networkInterface.use([
{
applyMiddleware(req, next) {
if (!req.options.headers) {
req.options.headers = {}; // Create the header object if needed.
}
req.options.headers.authorization = localStorage.getItem(AUTH_TOKEN);
next();
}
}
]);
export function provideClient(): ApolloClient {
return new ApolloClient({
networkInterface,
dataIdFromObject: (o: any) => `${o.__typename}-${o.id},`
});
}
当我注销我有这样的代码
localStorage.removeItem(AUTH_TOKEN);
this._apollo.getClient().resetStore();
然后当我发出另一个请求时,它仍然在请求头中使用旧的令牌。
如何使用新令牌进行更新?
答
我可能会中间件改成这样:
networkInterface.use([{
applyMiddleware(req, next) {
if (!req.options.headers) req.options.headers = {}
const token = localStorage.getItem('token')
req.options.headers.authorization = token ? token : null
next()
}
}])
注意三元运算符在那里,token ? token : null
。这将确保auth头部不能被发送,除非应用知道令牌。如果您的客户端仍在发送它,那么令牌不会被正确删除。
你也可以尝试这个快速测试:注销后,按F12键入浏览器控制台:localStorage
并查看令牌是否仍在那里。
我不能告诉你的代码,但它看起来像你有一个名为AUTH_TOKEN的变量,它返回一个类似'token'的字符串或你使用的任何键。我只是想明确提到你是通过密钥而不是价值来移除令牌的。
添加标记:localStorage.setItem('token', 'e47nes45nysde5nue5nu')
删除标记:localStorage.removeItem('token')
如果你的代码是这样的:
const AUTH_TOKEN = 'e47nes45nysde5nue5nu'
localStorage.removeItem(AUTH_TOKEN)
那么,这就是为什么它仍与身份验证令牌进行查询。我不认为它会在控制台中生成错误,如果它找不到从localStorage中删除的匹配键。