【发布时间】:2021-08-26 00:17:27
【问题描述】:
在实现 GraphQL 身份验证模块时,解析器通过 RESTDataSource 调用外部 API。
async logout() {
return await this.post('/logout', { credentials: 'include' })
}
这将返回一个空的主体对象(预期)和包含 * Set-Cookie: access_token=; Path=/; Expires=Thu, 01 Jan 1970 00:00:00 GMT 的标头
预期结果是access_token cookie 从浏览器中删除。如果这是直接使用 fetch 调用的,那么它会发生,但在通过 GraphQL 完成时不会发生。
设置如下:
# Resolver
Mutation: {
logout: async (_parent, _args, context) => {
const api = context.injector.get(UserAPI);
const response = await api.logout();
return response;
},
},
和服务器...
# Apollo Server
function apolloGraphqlServer(app: Express) {
const server = new ApolloServer({
schema,
context: ({ req }): { token: string } => {
return {
token: req.headers.authorization,
};
},
introspection: true,
});
server.applyMiddleware({ app });
}
和客户(在 Express 上)
const apolloClient = new ApolloClient({
cache: new InMemoryCache(),
link: new SchemaLink({
schema,
context: {
session: req,
token: authCookie ? `Bearer ${authCookie}` : null,
},
}),
credentials: 'include',
ssrMode: true,
});
如何根据响应删除 cookie
【问题讨论】:
标签: graphql apollo-client apollo-server express-graphql