【问题标题】:Querying graphiql leads Apollo error forward is not a function查询 graphiql 导致 Apollo 错误转发不是​​函数
【发布时间】:2019-03-26 09:12:57
【问题描述】:

我有一个使用 GraphQL 的快速后端,当我转到 /graphiql 并手动执行一些搜索时,它可以工作。我的 React 前端正在尝试在后端执行搜索。以下代码应异步执行查询:

const data = await this.props.client.query({
    query: MY_QUERY,
    variables: { initials: e.target.value }
});
console.log(data);

MY_QUERY 是之前定义的,它代表一个我知道有效且已在 /graphiql 上测试过的查询。为了在我的 React 组件中执行此操作,我将其导出为 export default withApollo(MyComponent),以便它在 props 中具有 client 变量。

index.js 文件中,我通过 Apollo 定义了到 /graphiql 的连接以执行查询:

//link defined to deal with errors, this was found online
const link = 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}`);
});

//the httpLink to my GraphQL instance, BASE_URL is defined elsewhere
const httpLink = new HttpLink({
    uri: BASE_URL,
    headers: {
    },
});

//here I define the client linking the GraphQL instance, the cache, and error handling
const client = new ApolloClient({
    link: httpLink,
    cache,
    link
});

在没有处理错误的link变量的情况下执行上述查询时,我从服务器(ApolloError.js:37 Uncaught (in promise) Error: Network error: Response not successful: Received status code 400)收到400 Bad Request。由于这并没有告诉我更多信息,因此在 StackOverflow 和 Apollo 网页上,我发现了上面输出 [Network error]: TypeError: forward is not a function 的错误声明。这个错误是什么意思,我该如何解决?

谢谢!

【问题讨论】:

    标签: graphql apollo react-apollo graphiql


    【解决方案1】:

    您的客户端配置有一个重复的属性——您首先将link 属性设置为HttpLink,然后再次将其设置为ErrorLink。这意味着 HttpLink 被完全忽略,您只需将 ErrorLink 传递给配置。您会看到该错误,因为由 onError 创建的 ErrorLink 并不打算单独使用。相反,它应该与HttpLink 链接,这就是您应该分配给link 属性的内容。

    This page 在文档中详细说明了如何正确组合链接。您可以使用concat,但我更喜欢ApolloLink.from,因为它可以让您清楚地显示链接的顺序:

    const errorLink = onError(...)
    const httpLink = new HttpLink(...)
    const link = ApolloLink.from([
      errorLink,
      httpLink,
    ])
    const client = new ApolloClient({
      link,
      cache,
    })
    

    【讨论】:

      猜你喜欢
      • 2018-06-27
      • 1970-01-01
      • 2018-08-17
      • 2017-05-19
      • 1970-01-01
      • 2022-01-21
      • 1970-01-01
      • 2018-07-09
      • 1970-01-01
      相关资源
      最近更新 更多