簡體   English   中英

使用 Apollo/GraphQL 在 header 中發送 JWT

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

我正在嘗試使用我的 graphql 請求在 header 中發送 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()
});

請求 URL: http://localhost:3000/graphql請求方法:POST 狀態代碼:404 未找到遠程地址:127.0.0.1:3000 推薦人策略:no-referrer-when-downgrade

這是請求 header。 我嘗試將其切換到 localhost:3001 但無論出於何種原因,它仍默認為 3000。

任何幫助表示贊賞!

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

你可以這樣做

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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM