更改 jwt 令牌的 Apollo Client 选项

Change Apollo Client options for jwt token

我想在用户登录时在我的 apollo 客户端中设置一个令牌。

这是我的 index.js:

const client = new ApolloClient({
        ssrMode: SERVER_MODE,
        cache: new InMemoryCache().restore(cache),
        link: createUploadLink({
            uri: process.env.REACT_APP_API_URL,
            fetch: SERVER_MODE ? global.fetch : NetworkService.customFetch,
            headers: {
                Authorization: 'Bearer ' + window.localStorage.access_token,
           }
        }),
        defaultOptions: NetworkService.defaultOptions,
    });

ReactDOM.render(
    <ApolloProvider client={client}>
        <Router>
            <App client={client}/>
        </Router>
    </ApolloProvider>,
    document.getElementById('root')
);

问题是,应用程序启动时没有令牌,因此客户端使用令牌初始化:null。

当用户登录时,我设置了令牌,但我需要以某种方式刷新我的应用程序以考虑令牌。

登录函数仅在成功登录 api 调用后将令牌保存在 localStorage 中。

我应该如何处理这个问题?现在,我正在登录后重新加载整个页面以绕过这个问题...

我使用了那里描述的 setContext 方法:http://dev.apollodata.com/react/auth.html#Header 并且效果很好!

static authLink = setContext((_, { headers }) => {
    // get the authentication token from local storage if it exists
    const token = localStorage.getItem('access_token');

    // return the headers to the context so httpLink can read them
    return {
        headers: {
            ...headers,
            authorization: token ? `Bearer ${token}` : '',
        }
    };
});

...

new ApolloClient({
    ssrMode: SERVER_MODE,
    cache: new InMemoryCache().restore(cache),
    link: ApolloLink.from([
        NetworkService.authLink,
        NetworkService.errorLink,
        NetworkService.uploadLink
    ]),
    defaultOptions: NetworkService.defaultOptions,
});