突变 returns 400 错误但在 GraphiQL 中有效

Mutation returns 400 error but works in GraphiQL

我一直在关注教程并尝试通过 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}]}]}

我的 "database" 是一个包含 const books

的 .js 文件

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

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

graphiql 可能对您的语法宽容,但对我来说它看起来不太正确。我希望是这样的:

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