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 请求。
嗨我有同样的问题,
红色:
Apollo Links 创建中间件,让您可以在请求发送到服务器之前对其进行修改
这是例子:
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)
| 归档时间: |
|
| 查看次数: |
8453 次 |
| 最近记录: |