首页 文章

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

提问于
浏览
2

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

Client code:

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);
    }
}

Schema code:

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
    }
`;

Resolver

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

The error

{"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书籍的.js文件

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

任何帮助将不胜感激,谢谢!

1 回答

  • 1

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

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

相关问题