拦截 Apollo/graphql 请求

eza*_*zay 6 error-handling apollo apollo-client angular express-graphql

我们在应用程序中使用 Apollo/Graphql,但遇到了一个问题。

该应用程序是在 Angular 5 中开发的,NodeJS 作为后端,graphql 服务器将响应前端。为了以 Angular 拦截 Http 请求,我们实现了“HttpInterceptor”,以便我们可以以自定义的方式处理错误。但是,Apollo 请求不会通过这个拦截器。

为了正确处理错误,我们使用了“apollo-link-error”。

但是我们想知道是否有可能以类似于 HttpInterceptor 的方式拦截 apollo 请求。

kct*_*ang 6

我认为拦截 Apollo Client 请求的官方方法是通过 Apollo Links。

但是,如果您使用 Angular,也可以通过 HttpInterceptor 来完成此操作。您可以查看我发布的这篇文章,介绍如何在使用 Apollo 客户端时使用 Angular 的 HttpInterceptor 管理访问/刷新令牌。

希望这可以帮助。


ALG*_*GDB 2

嗨我有同样的问题,

红色:

Apollo Links 创建中间件,让您可以在请求发送到服务器之前对其进行修改

阿波罗中间件

阿波罗2.0认证

这是例子:

import { HttpHeaders } from '@angular/common/http';
import { Apollo } from 'apollo-angular';
import { HttpLink } from 'apollo-angular-link-http';
import { setContext } from 'apollo-link-context';
import { InMemoryCache } from 'apollo-cache-inmemory';

@NgModule({ ... })
class AppModule {
  constructor(
    apollo: Apollo,
    httpLink, HttpLink
  ) {
    const http = httpLink.create({uri: '/graphql'});

    const auth = setContext((_, { headers }) => {
      // get the authentication token from local storage if it exists
      const token = localStorage.getItem('token');
      // return the headers to the context so httpLink can read them
      // in this example we assume headers property exists
      // and it is an instance of HttpHeaders
      if (!token) {
        return {};
      } else {
        return {
          headers: headers.append('Authorization', `Bearer ${token}`)
        };
      }
    });

    apollo.create({
      link: auth.concat(http),
      // other options like cache
    });
  }
}
Run Code Online (Sandbox Code Playgroud)