【问题标题】:Apollo Query Works in GraphIQL but Not in Call to graphql()?Apollo 查询在 GraphIQL 中有效,但在调用 graphql() 时无效?
【发布时间】:2017-02-25 18:02:51
【问题描述】:

我有一个在 localhost:3010/graphiql: 中正常工作的 Apollo 查询:

查询

query getIMs($fromID: String!, $toID: String!){
  instant_message(fromID:$fromID, toID: $toID){
    fromID,
    toID,
    msgText
  }
}  

查询变量

{
  "fromID": "1",
  "toID": "2"
}

这是我通过调用 graphql() 运行查询的代码:

const GETIMS_QUERY = gql`
query getIMs($fromID: String!, $toID: String!){
  instant_message(fromID:$fromID, toID: $toID){
    fromID,
    toID,
    msgText
  }
}  `;


const CreateIMPageWithDataAndMutations = graphql(GETIMS_QUERY, {
    options({ toID, userID }) {
        return {
            variables: { fromID: `${userID}`, toID: `${toID}`}
        };
    }
})(CreateIMPageWithMutations);

Chrome 网络选项卡显示预期的请求负载:

operationName:"getIMs" query: "query getIMs($fromID: String!, $toID: 字符串!) {↵ instant_message(fromID: $fromID, toID: $toID) {↵
fromID↵ toID↵ msgText↵ __typename↵ }↵}↵" 变量:{fromID:“DsmkoaYPeAumREsqC”,toID:“572bddac4ecbbac0ffe37fdd”} 来自ID:“DsmkoaYPeAumREsqC” toID:"572bddac4ecbbac0ffe37fdd"

但是data 对象返回时出现 ApolloError:

“网络错误:JSON 中位置 0 的意外令牌

我该如何纠正这个问题?

更新

这是“网络”选项卡的屏幕截图:

【问题讨论】:

  • 看起来您正在从服务器获取 HTML 作为响应。确保您的服务器接受 JSON 字符串 变量的对象。 graphiql 发送一个 JSON 字符串,Apollo 发送一个对象,你的服务器应该处理这两种情况。
  • Apollo Server 中的设置在哪里纠正这个问题?
  • 如果您使用的是 Apollo Server,should already 接受字符串和对象“变量可以是对象或 JSON 编码的字符串”。查看chrome网络请求,服务器的响应是什么?
  • 在“响应标头”旁边的“查看源代码”中:…我点击了“响应标头”旁边的“查看源代码”:> HTTP/1.1 200 OK > content-type: text/html; charset=utf-8 > 变化:接受编码 > 内容编码:gzip > 日期:星期一,2016 年 10 月 17 日 17:14:02 GMT > 连接:保持活动 > 传输编码:分块
  • 不查看源代码。在您的应用程序上执行 GraphQL 查询后,请查看开发者控制台中的 Network 选项卡。您应该会看到对 GraphQL 端点的请求。这将向您显示 Apollo 发出的 XHR 请求的响应。

标签: graphql apollo apollostack


【解决方案1】:

在 Marc Greenstock 和 @neophi 的帮助下,我找到了答案。我有这段代码设置了 Apollo 客户端:

const networkInterface = createNetworkInterface({
    uri: '/graphql',
    opts: {
        credentials: 'same-origin',
    },
    transportBatching: true,
});

这是相对定义 uri 并使用 Meteor 运行的相同端口 (3000)。但是 GraphQL 服务器当然运行在不同的端口上,在我的例子中是 3010。这修复了它:

const networkInterface = createNetworkInterface({
    uri: 'http://localhost:3010/graphql',
    opts: {
        credentials: 'same-origin',
    },
    transportBatching: true,
});

【讨论】:

    猜你喜欢
    • 2017-01-21
    • 2020-09-24
    • 2018-06-24
    • 2020-07-13
    • 2013-01-24
    • 1970-01-01
    • 2014-07-30
    • 2016-07-04
    • 1970-01-01
    相关资源
    最近更新 更多