在React和NodeJS中未经授权的重定向之前刷新令牌

时间:2018-11-22 20:02:58

标签: reactjs apollo react-apollo apollo-client apollo-server

是否有使用Apollo进行令牌刷新流程的示例?我有一个网站可以重定向没有令牌且需要刷新的用户,然后再重定向。

1 个答案:

答案 0 :(得分:0)

您可以检查软件包apollo-link-error的文档。

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(),
              },
            });
            // retry the request, returning the new observable
            return forward(operation);
        }
      }
    }
    if (networkError) {
      console.log(`[Network error]: ${networkError}`);
      // if you would also like to retry automatically on
      // network errors, we recommend that you use
      // apollo-link-retry
    }
  }
);