【问题标题】:Apollo/GraphQL Mutation Works in GraphIQL, but Not in Client Code?Apollo/GraphQL 突变在 GraphIQL 中有效,但在客户端代码中无效?
【发布时间】:2017-01-21 16:38:42
【问题描述】:

我在 http://localhost:8080/graphiql 的 GraphIQL 中让这个突变正常工作:

查询

mutation($fromID: String!, $toID: String!, $msgText: String!){
  createIM(fromID: $fromID, toID: $toID, msgText: $msgText){
    fromID
    toID
    msgText
  }
}

...和查询变量

{
  "fromID": "1",
  "toID": "2",
  "msgText": "Test from GraphIQL #3. It's working!!!"
}

现在我需要在代码中实现它。

客户代码

sendInstantMsg(){
    const {textToSend} = this.refs;
    const {toID} = this.props;

    const fromID = Meteor.userId();
    const msgText = trimInput(textToSend.getValue());

    client.query({
        query: gql`
            query mutation($fromID: String!, $toID: String!, $msgText: String!){
                createIM(fromID: $fromID, toID: $toID, msgText: $msgText){
                    fromID
                    toID
                    msgText
                }
            }
        `,
        variables: {
            fromID: fromID,
            toID: toID,
            msgText: msgText
        },
        forceFetch: false,
    }).then(({ data }) => {
        console.log('got data', data);
    }).catch((error) => {
        console.log('there was an error sending the query', error);
    });
}

查询变量(fromID、toID和msgText)按预期进入函数,但Apollo抛出错误:

message: "Network error: Unexpected token < in JSON at position 0"

我错过了什么?

【问题讨论】:

  • 查看 chrome 网络选项卡 - 你能在其中看到请求吗?它命中了什么 URL,返回值是多少?
  • 请求网址:localhost:3000/graphql。推荐人:localhost:3000/create_im/572bddac4ecbbac0ffe37fdf。请求负载:{"query":"query mutation($fromID: String!, $toID: String!, $msgText: String!) {\n createIM(fromID: $fromID, toID: $toID, msgText: $msgText) {\n fromID\n toID\n msgText\n }\n}\n","variables":{"fromID":"s9trFBxQcpaCjnon2","toID":"572bddac4ecbbac0ffe37fdf","msgText":"Testing 123"} “操作名称”:“突变”}。我在哪里可以找到返回值?
  • 在包含引用代码的文件中,我通过import ApolloClient from 'apollo-client'; const client = new ApolloClient(); 访问ApolloClient。这足以访问之前定义的解析器吗?

标签: graphql apollostack


【解决方案1】:

请改用这个.. 您应该使用 mutate 进行突变而不是查询..

client.mutate({
            mutation: gql`
                mutation createIM($fromID: String!, $toID: String!, $msgText: String!){
                    createIM(fromID: $fromID, toID: $toID, msgText: $msgText){
                        fromID
                        toID
                        msgText
                    }
                }
            `,
            variables: {
                fromID: fromID,
                toID: toID,
                msgText: msgText
            },
            forceFetch: false,
        }).then(({ data }) => {

【讨论】:

    猜你喜欢
    • 2023-04-09
    • 2017-02-25
    • 2017-08-01
    • 2022-06-23
    • 2021-12-28
    • 2018-08-04
    • 2019-11-21
    • 2018-05-21
    • 2019-02-02
    相关资源
    最近更新 更多