【问题标题】:Sending a JWT in header with Apollo/GraphQL使用 Apollo/GraphQL 在标头中发送 JWT
【发布时间】:2020-02-01 04:51:50
【问题描述】:

我正在尝试使用我的 graphql 请求在标头中发送 JWToken。

我已经关注了 Apollo 文档,但无论出于何种原因,它默认请求为“http://localhost:3000/graphql”而不是“http://localhost:3001/graphql

const httpLink = createHttpLink({
  uri: 'http://localhost:3001/graphql',
  credentials: 'include'
});

const authLink = setContext((_, { headers }) => {

  const token = localStorage.getItem('token');

  return {
    headers: {
      ...headers,
      authorization: token ? `Bearer ${token}` : "",
    }
  }
});

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

请求网址:http://localhost:3000/graphql 请求方法:POST 状态码:404 未找到 远程地址:127.0.0.1:3000 推荐人政策:降级时无推荐人

这是请求标头。我尝试将其切换到 localhost:3001,但无论出于何种原因,它仍然默认为 3000。

感谢任何帮助!

【问题讨论】:

    标签: reactjs http graphql


    【解决方案1】:

    你可以这样做

    const createApolloClient = (authToken) => {
      return new ApolloClient({
        link: new HttpLink({
          uri: 'your url',
          headers: {
            Authorization: `Bearer ${authToken}`
          }
        }),
        cache: new InMemoryCache(),
      });
     };
    

    然后这样称呼它

    const token = localStorage.getItem('token'); 
      const client = createApolloClient(token);
       return (
        <ApolloProvider client={client}>
           <div>
           </div>
        </ApolloProvider>
    

    【讨论】:

      【解决方案2】:

      需要从 apollo-client 使用 ApolloClient 而不是 apollo-boost

      【讨论】:

        猜你喜欢
        • 2014-09-02
        • 2016-07-12
        • 2017-10-07
        • 2018-08-21
        • 2020-02-22
        • 2015-04-25
        • 2021-07-22
        • 1970-01-01
        相关资源
        最近更新 更多