Apollo / GraphQL Mutation在GraphIQL中工作,但不在客户端代码中?

时间:2016-09-14 00:31:23

标签: graphql apollostack

我在http://localhost:8080/graphiql的GraphIQL中正确使用此突变:

QUERY

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

...和QUERY VARIABLES

{
  "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"

我错过了什么?

1 个答案:

答案 0 :(得分: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 }) => {