【问题标题】:GraphQL / Apollo - Can't get NetworkErrorGraphQL / Apollo - 无法获取 NetworkError
【发布时间】:2019-07-19 00:06:48
【问题描述】:

我的 Apollo 客户端无法收到任何网络错误,只有 GraphQL 错误。

我的客户端是这样设置的:

    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}`);
});

  const client = new ApolloClient({
    link: ApolloLink.from([
      errorLink,
      new HttpLink({
        uri: 'http://localhost:4000/graphql'
      }),
    ]),
  });

在服务器上我发出一个请求,我会这样解析:

 .then(res => {
  if (res.ok) {
    return { blah: res.json(), count };
  }
  throw new Error();
})
.catch(error => {
  throw new AuthenticationError('Must Authenticate');
});

AuthenicationError 只是作为 GraphQL 错误冒泡到客户端([GraphQL error]: Message: Must Authenticate,,我基本上只是希望能够在客户端从服务器请求中获取 HTTP 状态代码。

谢谢

【问题讨论】:

    标签: express graphql apollo apollo-client apollo-server


    【解决方案1】:

    您的客户端实现看起来正确。

    我猜你正在使用 express 和一些 graphl 中间件来处理请求。主要的是,您需要在 graphql 中间件发挥作用之前处理身份验证过程。

    因此,身份验证是您直接处理的 graphql 突变。就我而言,它看起来像这样:

    ...
    
    const app = express();
    
    app.use(
      "/graphql",
      bodyParser.json(),
      (request, response, next) => authenticationMiddleware(request) // authentication is handled before graphql
      .then(() => next())
      .catch(error => next(error)),
      graphqlExpress(request => {
        return {
          schema: executable.schema,
          context: {
            viewer: request.headers.viewer
          },
        };
      }),
    );
    
    ...
    
    app.listen(...)

    另一种可能性是将状态代码添加到 graphql 错误中的错误响应中。 但这取决于您使用的 npm 包。 例如apollo-server-graphql 中的格式错误 https://www.apollographql.com/docs/apollo-server/api/apollo-server.html#constructor-options-lt-ApolloServer-gt

    【讨论】:

      猜你喜欢
      • 2021-09-18
      • 1970-01-01
      • 1970-01-01
      • 2020-12-17
      • 2019-11-16
      • 2021-07-06
      • 2018-09-18
      • 1970-01-01
      • 2019-05-12
      相关资源
      最近更新 更多