所以我们正在使用 Apollo 和 GraphQL 创建一个 React-Native 应用程序。我正在使用基于 JWT 的身份验证(当用户同时登录activeToken和refreshToken 时),并希望实现一个流程,当服务器注意到它已过期时,令牌会自动刷新。
Apollo-Link-Error 的 Apollo Docs 提供了一个很好的起点来捕获来自 ApolloClient 的错误:
onError(({ graphQLErrors, networkError, operation, forward }) => {
if (graphQLErrors) {
for (let err of graphQLErrors) {
switch (err.extensions.code) {
case 'UNAUTHENTICATED':
// error code is set to UNAUTHENTICATED
// when AuthenticationError thrown in resolver
// modify the operation context with a new token
const oldHeaders = operation.getContext().headers;
operation.setContext({
headers: {
...oldHeaders,
authorization: getNewToken(),
},
});
// …
Run Code Online (Sandbox Code Playgroud)