2

我一直在学习教程并尝试使用 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书籍的 .js 文件

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

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

4

1 回答 1

1

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

var mutation = `
    mutation AddBook($author: String!, $title: String!, $src: String!) {
        addBook(author: $author, title: $title, src: $src) {
            id
            title
        }
    } 
`;
于 2018-02-24T22:29:00.050 回答