简体   繁体   English

使用 Apollo/GraphQL 在 header 中发送 JWT

[英]Sending a JWT in header with Apollo/GraphQL

I'm trying to send a JWToken in the header with my graphql requests.我正在尝试使用我的 graphql 请求在 header 中发送 JWToken。

I've followed the Apollo docs for it, but for whatever reason, it's defaulted the request to " http://localhost:3000/graphql " instead of " http://localhost:3001/graphql "我已经关注了 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()
});

Request URL: http://localhost:3000/graphql Request Method: POST Status Code: 404 Not Found Remote Address: 127.0.0.1:3000 Referrer Policy: no-referrer-when-downgrade请求 URL: http://localhost:3000/graphql请求方法:POST 状态代码:404 未找到远程地址:127.0.0.1:3000 推荐人策略:no-referrer-when-downgrade

this is the request header.这是请求 header。 I've tried switching it to localhost:3001 but for whatever reason it's still defaulting to 3000.我尝试将其切换到 localhost:3001 但无论出于何种原因,它仍默认为 3000。

any help is appreciated!任何帮助表示赞赏!

Needed to use ApolloClient from apollo-client and not apollo-boost需要从 apollo-client 使用 ApolloClient 而不是 apollo-boost

you can do this你可以这样做

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

and call it like this并这样称呼它

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM