找不到问题所在:SyntaxError:Object.register处的JSON输入意外结束[作为mutationFn](api-clients.ts:16:41)

问题描述 投票:0回答:1

`我一直在跟踪项目中的代码,一切进展顺利,直到遇到此错误,其中我的代码与工作模型完全相同,但它不起作用。

根据错误,它涉及 Mutate 函数,这是我认为包含错误的两个文件。目的只是将前端连接到后端,以允许用户通过填写注册表单进行注册

注册.tsx

import {useForm} from 'react-hook-form';
import { useMutation } from 'react-query';
import * as apiClient from '../api-clients'

// typescript type
export type RegisterFormData = {
  firstName: string;
  lastName: string;
  email: string;
  password: string;
  confirmPassword: string;
}

const Register = () => {

  const {register, watch, handleSubmit, formState:{errors},} = useForm<RegisterFormData>();

  // REACT-QUERY : Makes a request mutates or creates, post, put or delete 
// const mutation = useMutation(apiClient.register, {
//   onSuccess: () => {
//     console.log("Registration Successful");
//   }, 
//   onError: (error: Error) => {
//     console.log(error.message);
//   }
// });

const mutation = useMutation(apiClient.register, {
  onSuccess: () => {
  console.log("Registration Successful");
   

 
  },
  onError: (error: Error) => {
    console.log(error.message);
  },
});


// formData > mutate function > apiClient with the data
 
const onSubmit = handleSubmit((data) => {
  mutation.mutate(data);
});

return (
  <form className="flex flex-col gap-5" onSubmit={onSubmit}>
    <h2 className="text-3xl font-bold">Create an Account</h2>
    <div className="flex flex-col md:flex-row gap-5">
      <label className="text-gray-700 text-sm font-bold flex-1">
        First Name
        <input
          className="border rounded w-full py-1 px-2 font-normal"
          {...register("firstName", { required: "This field is required" })}
        ></input>
        {errors.firstName && (
          <span className="text-red-500">{errors.firstName.message}</span>
        )}
      </label>
      <label className="text-gray-700 text-sm font-bold flex-1">
        Last Name
        <input
          className="border rounded w-full py-1 px-2 font-normal"
          {...register("lastName", { required: "This field is required" })}
        ></input>
        {errors.lastName && (
          <span className="text-red-500">{errors.lastName.message}</span>
        )}
      </label>
    </div>
    <label className="text-gray-700 text-sm font-bold flex-1">
      Email
      <input
        type="email"
        className="border rounded w-full py-1 px-2 font-normal"
        {...register("email", { required: "This field is required" })}
      ></input>
      {errors.email && (
        <span className="text-red-500">{errors.email.message}</span>
      )}
    </label>
    <label className="text-gray-700 text-sm font-bold flex-1">
      Password
      <input
        type="password"
        className="border rounded w-full py-1 px-2 font-normal"
        {...register("password", {
          required: "This field is required",
          minLength: {
            value: 6,
            message: "Password must be at least 6 characters",
          },
        })}
      ></input>
      {errors.password && (
        <span className="text-red-500">{errors.password.message}</span>
      )}
    </label>
    <label className="text-gray-700 text-sm font-bold flex-1">
      Confirm Password
      <input
        type="password"
        className="border rounded w-full py-1 px-2 font-normal"
        {...register("confirmPassword", {
          validate: (val) => {
            if (!val) {
              return "This field is required";
            } else if (watch("password") !== val) {
              return "Your passwords do no match";
            }
          },
        })}
      ></input>
      {errors.confirmPassword && (
        <span className="text-red-500">{errors.confirmPassword.message}</span>
      )}
    </label>
    <span>
      <button
        type="submit"
        className="bg-blue-600 text-white p-2 font-bold hover:bg-blue-500 text-xl"
      >
        Create Account
      </button>
    </span>
  </form>
);
};

export default Register;

api-clients.ts

import { RegisterFormData } from "./pages/Register";

const API_BASE_URL = import.meta.env.VITE_API_BASE_URL;

// function accepts formData, helps in maintaining types of each field
export const register = async (formData: RegisterFormData) => {
    const response = await fetch(`${API_BASE_URL}/api/users/register`, {
      method: "POST",
      credentials: "include",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(formData),
    });
  
    const responseBody = await response.json();
  
    if (!response.ok) {
      throw new Error(responseBody.message);
    }
  };

当我点击提交按钮时,我收到错误:

javascript reactjs node.js typescript react-fullstack
1个回答
0
投票

我也有同样的问题。我通过以下步骤解决了这个问题

  1. api-client.ts 保存在 src 文件夹中
  2. .env 文件保存在前端文件夹中
© www.soinside.com 2019 - 2024. All rights reserved.