试图在GraphQL中添加课程的不良要求

发布于 2025-01-20 06:28:57 字数 3190 浏览 2 评论 0原文

我正在研究一个类项目,在该项目中,我正在使用Apoll Server在后端使用Apoll Server创建一个Fullstack网站,并为前端做出反应。我试图允许用户注册,然后从其仪表板页面添加一门课程。目前,该课程只有Coursetitle,Description和Creator是用户ID。我能够从GraphQL操场上添加一门课程,但是当我从前端尝试它时,我会发现一个错误:

index.ts:58 Uncaught (in promise) Error: Response not successful: Received status code 400

我已经浏览了所有代码,并将其与其他代码进行了比较,以签署有效的用户,但我无法获得Anotgher除了那个错误。我尝试将控制台.log放入解析器突变中,但一无所获,所以它根本不会击中分辨率。

这是我的添加解析器突变:

export const CREATE_COURSE = gql`
  mutation addCourse(
    $courseTitle: String!
    $description: String!
    $creator: String!
  ) {
    addCourse(
      courseTitle: $courseTitle
      description: $description
      creator: $creator
    ) {
      _id
      courseTitle
      description
      creator {
        _id
        firstName
      }
    }
  }
`;

这是解析器突变:

addCourse: async (parent, args, context) => {
      //if (context.user) {
      const course = await Course.create(args);
      return course;
      //}
    },

这是Typedef

const { gql } = require("apollo-server-express");
const typeDefs = gql`
  type User {
    _id: ID!
    email: String
    firstName: String
    lastName: String
    createdCourses: [Course]
    enrolledCourseIds: [ID]
    enrolledCourses: [Course]
  }

  type Course {
    _id: ID
    courseTitle: String!
    description: String!
    creator: User
  }

  type Mutation {
    addCourse(
      courseTitle: String!
      description: String!
      creator: String!
    ): Course
  }
`;
// export the typeDef
module.exports = typeDefs;

这是添加课程形式:

import { Form, Field } from "react-final-form";
import { useMutation } from "@apollo/client";
import { useNavigate } from "react-router-dom";
import { CREATE_COURSE } from "../utils/mutations";

export const CreateCourse = () => {
  const [addCourseMutation] = useMutation(CREATE_COURSE);
  const navigate = useNavigate();

  return (
    <Form
      onSubmit={async (values) => {
        await addCourseMutation({
          variables: {
            ...values,
          },
          onCompleted: (data) => {
            console.log(data);
            navigate("/dashboard");
          },
        });
      }}
      initialValues={{
        courseTitle: "",
        description: "",
      }}
      render={({ values, handleSubmit, form }) => {
        return (
          <div>
            <br />
            <br />
            <h1>Course Title</h1>
            <Field name="courseTitle" component="input" />
            <h1>Description</h1>
            <Field name="description" component="input" />
            
            
            <button
              disabled={
                values?.password?.length === 0 || values?.email?.length === 0
              }
              onClick={async () => {
                await handleSubmit();
                form.reset();
              }}
            >
              Submit
            </button>
          </div>
        );
      }}
    />
  );
};

我做了一系列更改,试图为创建者提供用户ID并将其带走,因为我什么都没买,但是现在,同样的错误我做了什么。

I am working on a class project where I am creating a fullstack website using Apoll Server with express on the back end and React for the front end. I am trying to allow users to sign up and then from their dashboard page add a course. Right now the course just have courseTitle, description, and creator which is the user's id. I am able to add a course from the graphql playground but when I try it from the front end I get an error:

index.ts:58 Uncaught (in promise) Error: Response not successful: Received status code 400

I have gone over all the code and compared it to other code for signing up a user which works but I cannot get anotgher other than that error. I tried putting a console.log in resolver mutation but get nothing so somehow it isn't hitting the resolver at all.

Here is my addCourse resolver mutation:

export const CREATE_COURSE = gql`
  mutation addCourse(
    $courseTitle: String!
    $description: String!
    $creator: String!
  ) {
    addCourse(
      courseTitle: $courseTitle
      description: $description
      creator: $creator
    ) {
      _id
      courseTitle
      description
      creator {
        _id
        firstName
      }
    }
  }
`;

Here is the resolver mutation:

addCourse: async (parent, args, context) => {
      //if (context.user) {
      const course = await Course.create(args);
      return course;
      //}
    },

Here is the typeDef

const { gql } = require("apollo-server-express");
const typeDefs = gql`
  type User {
    _id: ID!
    email: String
    firstName: String
    lastName: String
    createdCourses: [Course]
    enrolledCourseIds: [ID]
    enrolledCourses: [Course]
  }

  type Course {
    _id: ID
    courseTitle: String!
    description: String!
    creator: User
  }

  type Mutation {
    addCourse(
      courseTitle: String!
      description: String!
      creator: String!
    ): Course
  }
`;
// export the typeDef
module.exports = typeDefs;

This is the add course form:

import { Form, Field } from "react-final-form";
import { useMutation } from "@apollo/client";
import { useNavigate } from "react-router-dom";
import { CREATE_COURSE } from "../utils/mutations";

export const CreateCourse = () => {
  const [addCourseMutation] = useMutation(CREATE_COURSE);
  const navigate = useNavigate();

  return (
    <Form
      onSubmit={async (values) => {
        await addCourseMutation({
          variables: {
            ...values,
          },
          onCompleted: (data) => {
            console.log(data);
            navigate("/dashboard");
          },
        });
      }}
      initialValues={{
        courseTitle: "",
        description: "",
      }}
      render={({ values, handleSubmit, form }) => {
        return (
          <div>
            <br />
            <br />
            <h1>Course Title</h1>
            <Field name="courseTitle" component="input" />
            <h1>Description</h1>
            <Field name="description" component="input" />
            
            
            <button
              disabled={
                values?.password?.length === 0 || values?.email?.length === 0
              }
              onClick={async () => {
                await handleSubmit();
                form.reset();
              }}
            >
              Submit
            </button>
          </div>
        );
      }}
    />
  );
};

I made a bunch of changes trying to get the user Id for creator and took them out since I wasn't geting anything but that same error now matter what I did.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

心凉 2025-01-27 06:28:57

我意识到我没有从表单提交表单中发送用户_id,因此我将用户ID态度并将其设置在初始状态,因此将其传递给解析器。也许不是最好的方法,但我使它起作用。

import jwt from "jwt-decode";
import Auth from "../utils/auth";
import { Form, Field } from "react-final-form";
import { useMutation } from "@apollo/client";
import { useNavigate } from "react-router-dom";
import { CREATE_COURSE } from "../utils/mutations";

export const CreateCourse = () => {
  const token = Auth.loggedIn() ? Auth.getToken() : null;
  const user = jwt(token);

  const [addCourseMutation] = useMutation(CREATE_COURSE);
  const navigate = useNavigate();

  return (
    <Form
      onSubmit={async (values) => {
        await addCourseMutation({
          variables: {
            ...values,
          },
          onCompleted: (data) => {
            console.log(data);
            navigate("/courses");
          },
        });
      }}
      initialValues={{
        courseTitle: "",
        description: "",
        creator: user.data._id,
      }}
      render={({ values, handleSubmit, form }) => {
        return (
          <div>
            <br />
            <br />
            <h1>Course Title</h1>
            <Field name="courseTitle" component="input" />
            <h1>Description</h1>
            <Field name="description" component="input" />

            <button
              onClick={async () => {
                await handleSubmit();
                form.reset();
              }}
            >
              Submit
            </button>
          </div>
        );
      }}
    />
  );
};

I realized that I wasn't sending the user _id from the form the form submission so I gut the user Id and set it in the initial state so it was passed to the resolver. Maybe not be the best way to do it, but I got it working.

import jwt from "jwt-decode";
import Auth from "../utils/auth";
import { Form, Field } from "react-final-form";
import { useMutation } from "@apollo/client";
import { useNavigate } from "react-router-dom";
import { CREATE_COURSE } from "../utils/mutations";

export const CreateCourse = () => {
  const token = Auth.loggedIn() ? Auth.getToken() : null;
  const user = jwt(token);

  const [addCourseMutation] = useMutation(CREATE_COURSE);
  const navigate = useNavigate();

  return (
    <Form
      onSubmit={async (values) => {
        await addCourseMutation({
          variables: {
            ...values,
          },
          onCompleted: (data) => {
            console.log(data);
            navigate("/courses");
          },
        });
      }}
      initialValues={{
        courseTitle: "",
        description: "",
        creator: user.data._id,
      }}
      render={({ values, handleSubmit, form }) => {
        return (
          <div>
            <br />
            <br />
            <h1>Course Title</h1>
            <Field name="courseTitle" component="input" />
            <h1>Description</h1>
            <Field name="description" component="input" />

            <button
              onClick={async () => {
                await handleSubmit();
                form.reset();
              }}
            >
              Submit
            </button>
          </div>
        );
      }}
    />
  );
};
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文