我正在使用Apollo-Angular来设置与我的GraphQL端点的链接。我正在使用带有Authorization标头的JWT传递给端点。我遇到的问题是,当我第一次登录时,正在设置auth_token
cookie,但没有在我的Apollo链接中传递它。如果刷新页面,则一切正常,但是我无法弄清楚为什么登录后未通过该页面。就像链接标题只是在我登录之前在应用初始化时设置的,并且没有auth_token
cookie一样,它只是在标题中设置了一个空白的Authorization Bearer字符串,然后甚至在cookie之后也使用了它存在。我添加了一个Http Interceptor来记录请求,并确认没有添加令牌,即使我可以看到浏览器中已经设置了cookie。
这是我的graphql.module
,用于设置Apollo链接。有什么想法我做错了吗?
@NgModule({
exports: [ApolloModule, HttpLinkModule],
})
export class GraphQLModule {
constructor(
apollo: Apollo,
private cookieService: CookieService,
httpLink: HttpLink
) {
const headers = new HttpHeaders().set('Authorization', `Bearer ${cookieService.get('auth_token')}` || null);
// Create an http link:
const http = httpLink.create({
uri: 'http://localhost:8080/v1/graphql',
headers
});
// Create a WebSocket link:
const ws = new WebSocketLink({
uri: 'ws://localhost:8080/v1/graphql',
options: {
reconnect: true,
connectionParams: {
headers: { Authorization: `Bearer ${cookieService.get('auth_token')}` || null }
}
}
});
// Split links based on operation type
const link = split(
({ query }) => {
const definition = getMainDefinition(query);
return definition.kind === 'OperationDefinition' && definition.operation === 'subscription';
},
ws,
http,
);
apollo.create({
link: ApolloLink.from([
link
]),
cache: new InMemoryCache()
});
}