reactjs AxiosError:ERR_BAD_REQUEST in NextJS

hjqgdpho  于 5个月前  发布在  React
关注(0)|答案(2)|浏览(73)

我试图在我的NextJS应用程序开发一个登录系统.但我一直得到错误-

AxiosError {message:'Request failed with status code 400',name:'AxiosError',code:'ERR_BAD_REQUEST',config:{...},request:XMLHttpRequest,...}

在这里,我提供了与此主题相关的必要代码片段。
客户端(RegisterPage)-

const [authState, setAuthState] = useState({
    name: "",
    email: "",
    password: "",
    password_confirmation: "",
  });

  const [loading, setLoading] = useState<boolean>(false);
  const [errors, setErrors] = useState<registerErrorType>({});

  const submitForm = () => {
    setLoading(true);
    axios
      .post("http://localhost:3000/api/auth/register", authState)
      .then((res) => {
        setLoading(false);
        const response = res?.data;
        // debugger;
        if (response?.status == 200) {
          console.log("User created successfully");
        } else if (response?.status == 400) {
          setErrors(response?.errors);
        }
      })
      .catch((error: any) => {
        console.error("Axios request error:", error);
        setLoading(false);
      });
  };

字符串
服务器端(RegisterPage)-

export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const validator = vine.compile(registerSchema);
    const output = await validator.validate(body);
    validator.errorReporter = () => new ErrorReporter();
    // check if email already existes
    const user = await User.findOne({ email: output.email });
    if (user) {
      return NextResponse.json(
        {
          status: 400,
          errors: {
            email: "Email is already exists",
          },
        },
        { status: 200 }
      );
    } else {
      // Encrypt the password
      const salt = bcrypt.genSaltSync(10);
      output.password = bcrypt.hashSync(output.password, salt);
      await User.create(output);
      return NextResponse.json(
        { status: 200, message: "User created successfully" },
        { status: 200 }
      );
    }
  } catch (error) {
    if (error instanceof errors.E_VALIDATION_ERROR) {
      return NextResponse.json(
        { status: 400, errors: error.messages },
        { status: 400 }
      );
    }
  }
}


Thank you:)

rsl1atfo

rsl1atfo1#

这个问题有多个答案,你之前查过吗?我觉得你可能要把config也一起加进去,加一些相关的链接给你帮助。
1.https://stackoverflow.com/questions/72307388/axioserror-request-failed-with-status-code-400-in-react-js?rq=2,2.https://stackoverflow.com/questions/44731340/getting-400-error-bad-request-using-axios,3.https://stackoverflow.com/questions/73612522/react-upload-file-with-axios-gives-axioserror-code-err-bad-request?rq=2

5ktev3wc

5ktev3wc2#

有没有可能你的authState输入是错误的,被捕获并抛出一个验证错误?当它被发送到服务器时,你能做一个console.log()或在authState主体上放置一个断点吗?
另外,我会从使用更通用的try-catch开始,现在你正在对错误使用特定的catch,但只抛出验证错误(这似乎是这是关于什么的),但如果不是,那么错误将被吞噬,你的代码将崩溃。
此外,我知道这并不能解决你手头的具体问题,但在宏伟的计划中,可能值得考虑使用像NextAuthAuth 0这样的库来帮助你启动身份验证/授权工作。
希望这至少能给你一些思考的东西:-)

相关问题