简体   繁体   中英

Sending a JWT in header with Apollo/GraphQL

I'm trying to send a JWToken in the header with my graphql requests.

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 "

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

this is the request header. I've tried switching it to localhost:3001 but for whatever reason it's still defaulting to 3000.

any help is appreciated!

Needed to use ApolloClient from apollo-client and not 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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