将多个标头添加到graphql客户端(Apollo-boost)

时间:2020-03-18 12:28:43

标签: graphql apollo apollo-client apollo-boost

  const client = new ApolloClient({
    uri,
    onError: (e: any) => {
      console.log('error: ', e); // Failed to fetch
      console.log(e.operation.getContext()); // it does show it has x-abc-id
    },

    request: operation => {
      const headers: { [x: string]: string } = {};
      const accessToken = AuthService.getUser()?.accessToken;
      const activeClientId = UserService.getActiveClientId();
      headers['x-abc-id'] = activeClientId;
      if (accessToken) headers['Authorization'] = `Bearer ${accessToken}`;
      operation.setContext({ headers });
    }

});

这里的问题是,当我只添加 Authorization 标头时,它将进行POST调用并显示预期的错误。

但是当我添加 x-abc-id 标头(后端也期望它)时,它只会进行OPTIONS调用(无发布调用)

P.S。在邮递员上,添加两个标头都可以很好地工作。

1 个答案:

答案 0 :(得分:0)

找到了问题所在,并认为可以解决。

邮递员在向后端发送请求之前未执行OPTIONS call

在OPTIONS调用中,?表示客户端调用包含的内容:[授权,内容类型,x-abc-id] enter image description here

服务器期望什么: enter image description here

只需授权,内容类型 因此,这是呼叫标头不匹配(与Apollo无关)。

在后端的CORS配置中必须明确允许

x-abc-id标头

感谢Pooria Atarzadeh