首页 > 解决方案 > 节点获取时使用 RestDataSource 不会返回数据

问题描述

我正在使用 RestDataSource 从 api 获取数据。所有 'POST' 函数都工作并返回响应,但 'GET' 返回 401 错误。

constructor(@Inject(CONTEXT) context: GraphQLModules.GlobalContext) {
    super();
    super.initialize({ context, cache: new InMemoryLRUCache() });
    this.baseURL = process.env.APP_API_HOST;
  }

  willSendRequest(request: RequestOptions) {
    if (this.context.token) {
      request.headers.set('Authorization', this.context.token);
    }
  }

  async me() {
    return await this.get('/me');
  }

  async login({ email, password }: MutationLoginArgs) {
    return await this.post('/login', {
      email,
      password,
    });
  }

这是通过解析器调用的

 Query: {
    me: async (_parent, _args, context) => {
      const api = context.injector.get(AuthAPI);
      const reply = await api.me();
      return reply.result;
    },
  },

我得到的响应总是来自我们的 api 的 401。node-fetch但是,如果我像这样直接在解析器中拨打电话:

Query: {
    me: async (_parent, _args, context) => {
      const response = await fetch(`${process.env.APP_API_HOST}/me`, {
        headers: { Authorization: context.token },
      });
      const data = await response.json();
      return data.result;
    },
  },

然后这将返回我期望的对象。

两种方法都将令牌作为标头发送,因此不确定哪里出了问题,因此感谢您的帮助。

标签: graphqlapollo-clientapollo-serverrestdatasource

解决方案


推荐阅读