Mutation返回400错误但在GraphiQL中有效

时间:2018-02-24 22:20:06

标签: reactjs express graphql express-graphql

我一直在关注教程并尝试使用react和express来学习graphql,而且我遇到了麻烦。当我将其插入graphiql时,我的变异会起作用,但是当我从客户端调用它时,我的变异就不起作用了。

客户代码:

async addBook(params) {
    var title = params["title"];
    var author = params["author"];
    var src = params["src"];

    var mutation = `
        { addBook($author: String!, $title: String!, $src: String!) {
            addBook(author: $author, title: $title, src: $src) {
                id
                title
            }
        } 
    }`;

    const res = await fetch(this.apiUrl, {
        method: 'POST',
        mode: 'cors',
        headers: new Headers({
            'Content-Type': 'application/json',
            'Accept': 'application/json',
        }),
        body: JSON.stringify({
            query: mutation,
            variables: {author: author, title: title, src: src}
        }),
    });
    if (res.ok) {
        const body = await res.json();
        console.log(body.data);
        return body.data;
    } else {
        throw new Error(res.status);
    }
}

架构代码:

const typeDefs = `
    type Book {
        id: ID!
        author: String!
        title: String!
        src: String!

    }

    type Query {
        Books: [Book]
    }

    type Mutation {
        addBook(author: String, title: String, src: String): Book
    }
`;

解析器

Mutation: {
    addBook: (root, args) => {
        const newBook = {id: Books.length+1, author: args.author, title: args.title, src: args.src};
        Books.push(newBook);
        return newBook;
    },
},

错误

{"errors":[{"message":"Syntax Error GraphQL request (2:25) Expected Name, found $\n\n1: \n2:             { mutation ($author: String!, $title: String!, $src: String!) {\n                           ^\n3:                 addBook(author: $author, title: $title, src: $src) {\n","locations":[{"line":2,"column":25}]}]}

我的“数据库”是包含const books

的.js文件

我可以发送查询并获得结果,但突变似乎更难。

非常感谢任何帮助,谢谢!

1 个答案:

答案 0 :(得分:1)

graphiql可能对你的语法很宽容,但对我来说看起来不太正确。我希望这样的事情:

var mutation = `
    mutation AddBook($author: String!, $title: String!, $src: String!) {
        addBook(author: $author, title: $title, src: $src) {
            id
            title
        }
    } 
`;