【问题标题】:Unhandled Rejection (Error): Response not successful: Received status code 400 new ApolloError未处理的拒绝(错误):响应不成功:收到状态码 400 new ApolloError
【发布时间】:2021-09-05 02:01:26
【问题描述】:

我对@9​​87654321@ 很陌生。话不多说,上代码。我有一个正在运行的服务器,我正在尝试使用 react 进行突变。

server.js中的突变

const RootMutationType = new GraphQLObjectType({
  name: "RootMutation",
  description: "Root Mutation Type.",
  fields: () => ({
    addBook: {
      type: BookType,
      args: {
        authorId: { type: GraphQLID },
        name: { type: GraphQLString },
      },
      resolve: async (parent, args) => {
        const book = new Book({
          name: args.name,
          authorId: args.authorId,
        });
        return await book.save();
      },
    },
......
// other crazy stuff here 

使用graphiql 我可以添加一本书,这意味着服务器运行良好。但是在反应客户端上,当我尝试添加一本书时,我得到了错误。这是我所拥有的。

mutations.js

import { gql } from "@apollo/client";

const ADD_BOOK_MUTATION = gql`
  mutation addBook($authorId: Integer!, $name: String!) {
    addBook(authorId: $authorId, name: $name) {
      name
      id
    }
  }
`;

export { ADD_BOOK_MUTATION };

Form.jsx

import React, { useEffect, useRef } from "react";
import { useMutation } from "@apollo/client";
import { ADD_BOOK_MUTATION } from "./mutations";
const Index = () => {
  const [addBook, { data, error }] = useMutation(ADD_BOOK_MUTATION);
  const idRef = useRef(null);
  const nameRef = useRef(null);
  useEffect(() => {
    if (error) {
      console.error(error);
    } else {
      console.log(data);
    }
  }, [data, error]);
  const addBookHandler = (e) => {
    e.preventDefault();
    addBook({
      variables: {
        authorId: idRef.current.value,
        name: nameRef.current.value,
      },
    });
  };
  return (
    <form className="form">
      <input ref={idRef} type="number" placeholder="author id" />
      <input ref={nameRef} type="text" placeholder="book name" />
      <button onClick={addBookHandler}>addBook</button>
    </form>
  );
};
export default Index;

谁能告诉我我哪里错了!!帮助输入将不胜感激!

【问题讨论】:

    标签: javascript reactjs graphql apollo-client react-apollo


    【解决方案1】:

    通常这些类型的错误是由于突变参数类型与用户定义的 GraphQL 突变查询参数不匹配而引起的。

    例如,我写的突变查询缺少!,而突变的类型定义有!。

    【讨论】:

      【解决方案2】:

      我只是在一段时间后弄清楚自己。 $authorId: Integer! 应该是 $authorId:ID。

      新突变

      import { gql } from "@apollo/client";
      
      const ADD_BOOK_MUTATION = gql`
        mutation addBook($authorId: ID, $name: String!) {
          addBook(authorId: $authorId, name: $name) {
            name
            id
          }
        }
      `;
      
      export { ADD_BOOK_MUTATION };
      

      【讨论】:

        猜你喜欢
        • 2021-10-18
        • 2021-04-02
        • 2019-02-16
        • 2020-07-09
        • 2019-09-27
        • 1970-01-01
        • 2021-07-26
        • 2018-12-21
        • 2019-11-25
        相关资源
        最近更新 更多