【问题标题】:put JWT token in header for Apollo Client将 JWT 令牌放入 Apollo 客户端的标头中
【发布时间】:2021-01-15 03:42:05
【问题描述】:

目前,如果我从我的 react 应用程序运行 graphql 突变,它们将不起作用,因为标头中缺少授权令牌。我有一个要插入到标头中的管理机密,但我不知道该怎么做。

import { ApolloClient } from 'apollo-client';
import { InMemoryCache, NormalizedCacheObject } from 'apollo-cache-inmemory';
import { HttpLink } from 'apollo-link-http';
import { ApolloProvider } from '@apollo/react-hooks';
....
const cache = new InMemoryCache();
const link = new HttpLink({
  uri: 'https://api/graphql',
});

const client: ApolloClient<NormalizedCacheObject> = new ApolloClient({
  cache,
  link,
});
ReactDOM.render(
  <ThemeProvider theme={theme}>
    <CssBaseline />
    <ApolloProvider client={client}>
      <BrowserRouter>
        <App />
      </BrowserRouter>
    </ApolloProvider>
  </ThemeProvider>,
  document.querySelector('#root'),
);

我的 Apollo.config.js 文件中也有这个:

module.exports = {
    client: {
      service: {
        url: 'https://api/graphql',
        headers: {
          'x-hasura-admin-secret': 'xxx',
        },
      },
      excludes: ['src/graphql/index.tsx'],
    },
  };

如何在标头中包含令牌?应该是这样的:

'Authorization', `Bearer ${token}

在另一个 React Native 项目中也使用了相同的 API,他们获得了这样的令牌:

import auth from '@react-native-firebase/auth';
...
const token = await auth().currentUser?.getIdToken();

但我不知道如何在反应中实现这一点。

我也试过这样:

import { createHttpLink, InMemoryCache, ApolloClient } from '@apollo/client';
import { setContext } from '@apollo/client/link/context';

const httpLink = createHttpLink({
  uri: 'https://graphql',
});

const authLink = setContext((_, { headers }) => {
  const token = 'XX';
  return {
    headers: {
      ...headers,
      authorization: token ? `Bearer ${token}` : "",
    }
  }
});

const client = new ApolloClient({
  link: authLink.concat(httpLink),
  cache: new InMemoryCache()
});

但我在这里得到一个错误:

<ApolloProvider client={client}>

那个:

Type 'ApolloClient<NormalizedCacheObject>' is missing the following properties from type 'ApolloClient<any>': store, writeData, initQueryManager

【问题讨论】:

  • 我已经尝试过了,但它在客户端 &lt;ApolloProvider client={client}&gt; 上给了我 Type 'ApolloClient&lt;NormalizedCacheObject&gt;' is missing the following properties from type 'ApolloClient&lt;any&gt;': store, writeData, initQueryManager。无论哪种方式,都可以在这里使用admin secret 作为令牌吗? @DanielA.White

标签: javascript reactjs graphql jwt apollo


【解决方案1】:

根据您的令牌在客户端上的存储位置,您可以试试这个


const authLink = setContext((_, { headers }) => {
  const token = localStorage.getItem("id");
  return {
    headers: {
      ...headers,
      authorization: token ? `Bearer ${token}` : "",
    },
  };
});

【讨论】:

  • 这些是我用来使其工作的导入import { ApolloClient, createHttpLink, InMemoryCache } from "@apollo/client"; import { setContext } from "@apollo/client/link/context";
  • 从您上面的帖子看来,我们使用了不同的软件包,当我开始使用您正在使用的导入时,我的 api 也出现了问题。 @Apollo 有多个文件夹可以访问。
  • 是的,我注释掉了我的并按照您的建议进行操作,使用相同的导入但仍然出现此错误。诡异的。您知道您使用的是哪个版本吗?
  • 4.0.0 是的,这很奇怪。这是我的 Apollo 文件的链接,也许会有所帮助。 codepen.io/niles87/pen/KKzLgWb
  • 直到这部分,我也没有收到错误。我只收到&lt;ApolloProvider client={client}&gt; 第一个客户字的错误。这是问题的代码返回部分
猜你喜欢
  • 2019-08-16
  • 2019-10-11
  • 2018-05-20
  • 2020-04-19
  • 2020-08-27
  • 2022-11-29
  • 2021-08-12
  • 2020-12-21
  • 2015-09-20
相关资源
最近更新 更多