【问题标题】:GraphQL/ React throws Network Error JSON.parse: unexpected character at line 1 column 1 of the JSON dataGraphQL/ React 抛出网络错误 JSON.parse:JSON 数据的第 1 行第 1 列出现意外字符
【发布时间】:2019-05-11 14:36:17
【问题描述】:

我有一个在 localhost:8080/someApplication/graphql 上运行的 Java GraphQL 端点(CORS 已激活),当我在 Altair(Firefox 插件)中编写查询时,我确实得到了一个有效的响应:

牵牛星

发布http://localhost:8080/someApplication/graphql

查询:

{
    someInformation
    {
        nameOfInformation
    }
}

返回:

{
    "data": {
        "someInformation": 
        [
          {
            "nameOfInformation": "hi"
          }
        ]
      },
      "errors": [],
      "dataPresent": true,
      "extensions": null
}

所以查询似乎工作得很好。

反应

我将我的 GraphQL 客户端 (localhost:3000) 配置如下:

const httpLink = createHttpLink({
    uri: "http://localhost:8080/someApplication/graphql",
});

const client = new ApolloClient({
    link: httpLink,
    cache: new InMemoryCache()
});

....
<ApolloProvider client={client}>
<Query query={gql`
    {
        someInformation{
            nameOfInformation
        }
    }
`}
>
    {({loading, error, data}) => {
        if (loading) return <p>Loading...</p>;

        if (error) return <p>{error.networkError.message}</p>;

        return data.someInformation.map(({nameOfInformation})=> (
            <p>{`${nameOfInformation}`}</p>
        ));
    }}
</Query>
</ApolloProvider>

结果

我总是收到以下错误:JSON.parse:JSON 数据的第 1 行第 1 列出现意外字符。

当我将代码更改为端点是 Apollo Launchpad 中的端点时,查询返回正确的结果并且没有抛出错误。

有什么方法可以查看返回的数据并导致错误的样子?或者我在接收数据时做错了什么? 我很感激这方面的任何帮助!感谢您对此进行调查!

【问题讨论】:

    标签: json reactjs error-handling graphql apollo


    【解决方案1】:

    问题出在服务器上:如果您通过 HTTP 配置了 GraphQL Endpint,则您的类必须具有以下注解:

    @Path("/your-path-here")
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public class yourClass {... }
    

    在我的情况下,传入的请求未被识别为 JSON,这是错误的原因。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-09-14
      • 2020-01-11
      • 2020-10-13
      • 2017-05-18
      • 2016-01-30
      • 2020-06-07
      • 2020-02-09
      相关资源
      最近更新 更多