Apollo Link中间件未向请求添加自定义标头

时间:2018-04-12 20:33:55

标签: http apollo react-apollo

我正在尝试通过Apollo中间件将auth令牌添加到我的所有http请求中。看来我的中间件永远不会被解雇。我正在localhost上访问服务器:8081,来自localhost:8080上的客户端。我是阿波罗的新手,所以我可能对ApolloLink有误解。

const httpLink = new HttpLink({ uri: 'http://localhost:8081/graphql' });

const getTokenMiddleware = new ApolloLink((operation, forward) => {
  operation.setContext(({ headers }) => ({
    headers: {
      ...headers,
      'x-token': localStorage.getItem('token') || null,
      'x-refresh-token': localStorage.getItem('refreshToken') || null,
    },
  }));

  return forward(operation);
});

const client = new ApolloClient({
  cache: new InMemoryCache(),
  link: from([
    getTokenMiddleware,
    httpLink
  ]),
  uri: 'http://localhost:8081/graphql',
});

这是我在服务器上获得的标题

headers: { 
     host: 'localhost:8081',
     connection: 'keep-alive',
     'content-length': '351',
     accept: '*/*',
     origin: 'http://localhost:8080',
     'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36',
     'content-type': 'application/json',
     dnt: '1',
     referer: 'http://localhost:8080/register',
     'accept-encoding': 'gzip, deflate, br',
     'accept-language': 'en-US,en;q=0.9' 
}

1 个答案:

答案 0 :(得分:0)

这是所需的不同步骤。我希望这可以解决您的问题

// 1 HttpLink that will connect your ApolloClient instance with the GraphQL API (If you have multiple URL's)
const httpLink = split(
  operation => operation.getContext().type === 'public',
  new HttpLink({ uri: `${GraphQLURLPublic}/query` }),
  new HttpLink({ uri: `${GraphQLURLPrivate}/query` }),
);

// 2 Added Middleware to Insert Authorization Header If Required
// Split URL to two different endpoints If the type is Private it will Token in header else it won't
const authLink = setContext((operation, previousContext) => {
  const { headers, type } = previousContext;
  if (type === 'public') {
    return previousContext;
  }

  //You access token to make call
  const accessToken = 'xtz'
  if (accessToken) {
    return {
      ...previousContext,
      headers: {
        ...headers,
        authorization: accessToken
      },
    };
  }

  return { ...previousContext };
});


// 3 Added error handling
const ErrorLink = onError(({ graphQLErrors, networkError }) => {
  if (graphQLErrors)
    graphQLErrors.map(({ message, locations, path }) =>
      console.log(
        `[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`,
      ),
    );

  if (networkError) console.log(`[Network error]: ${networkError}`);
});

// 4 concat all links, NOTE: httpLink must be last
const link = ApolloLink.from([authLink, ErrorLink, httpLink]);

// 5 Instantiate ApolloClient by passing in the composed link and a new instance of an InMemoryCache.
const graphqlConfig = new ApolloClient({ link, cache: new InMemoryCache(), queryDeduplication: false });