【问题标题】:Mutation returns 400 error but works in GraphiQL突变返回 400 错误,但在 GraphiQL 中有效
【发布时间】:2018-08-04 17:04:59
【问题描述】:

我一直在学习教程并尝试使用 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}]}]}

我的“数据库”是一个 .js 文件,其中包含一个 const books

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

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

【问题讨论】:

  • 您能粘贴从 400 错误返回的确切消息吗?您可能会在快速服务器的终端中收到有用的错误消息
  • 我已经用完整的错误更新了这个问题。我觉得这个错误没有出现在 GraphiQL 中很奇怪

标签: reactjs express graphql express-graphql


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2019-05-22
    • 2017-01-21
    • 2018-03-28
    • 2022-06-23
    • 2020-11-02
    • 2018-09-02
    • 1970-01-01
    • 2022-10-23
    • 2020-09-06
    相关资源
    最近更新 更多