数据未添加到数据库 mongodb

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

我试图获取与数据库链接的用户信息,但我的数据库中的数据没有更新。 我感觉我的数据没有从 api 传输到数据库

"use client";
import React from "react";
import { useState } from "react";

const Register = () => {
  const [name, setName] = useState("");
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const handleSubmit = async (e) => {
    e.preventDefault();
    await fetch("api/register", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        name: name,
        email: email,
        password: password,
      }),
    });
  };
  return (
    <div className="h-screen grid content-center justify-items-center">
      <div className="w-1/4  bg-accent2 text-black px-6 pb-5 pt-10 border-none rounded-lg ">
        <h1 className="text-white font-bold text-center text-2xl mb-10 ">
          Create your account
        </h1>
        <form className="flex flex-col " onSubmit={handleSubmit}>
          <input
            onChange={(e) => {
              setName(e.target.value);
            }}
            type="text"
            placeholder="Name"
            className="p-3 rounded-t-md border-2  border-t-accent border-r-accent border-l-accent"
          />
          <input
            onChange={(e) => {
              setEmail(e.target.value);
            }}
            type="text"
            placeholder="Email"
            className="p-3 border-2  border-r-accent border-l-accent"
          />
          <input
            onChange={(e) => {
              setPassword(e.target.value);
            }}
            type="password"
            placeholder="Password"
            className="p-3 mb-10 rounded-b-md border-2  border-b-accent border-r-accent border-l-accent"
          />
          <div className="flex justify-between text-white mb-5 ">
            <button
              type="submit"
              className=" bg-accent p-2 border-2 border-accent   rounded-full w-1/4 font-semibold transition btnHover"
            >
              Sign Up
            </button>
            <a href="/" className="text-sm ">
              Already have an account?{" "}
              <span className="text-accent">Log In</span>
            </a>
          </div>
        </form>
      </div>
    </div>
  );
};

export default Register;

这是api路由

import connectMongoDb from "@/lib/mongoDb";
import bcrypt from "bcrypt";
import User from "@/models/user";
import { NextResponse } from "next/server";

export async function POST(req) {
  try {
    const { name, email, password } = req.body.json();
    let hashPassword = "";
    bcrypt.hash(password, 10, function (err, hash) {
      hashPassword = hash;
      console.log(err);
    });
    await connectMongoDb();
    await User.create({
      name: name,
      email: email,
      password: hashPassword,
    });
    return NextResponse.json({ massage: "User regsitered." }, { status: 201 });
  } catch (error) {
    return NextResponse.json(
      { message: "An error occured while registering the user." },
      { stauts: 500 }
    );
  }
}

这是 mongoDB 模式

import mongoose, { Schema, models } from "mongoose";

const userSchema = new Schema(
  {
    name: { type: String, required: true },
    email: { type: String, required: true },
    password: { type: String, required: true },
  },
  { timestamps: true }
);

const User = models.User || mongoose.model("User", userSchema);
export default User;

希望我能得到快速解决?

我也收到请求状态,因为 200 不知道为什么会发生这种情况希望得到解决方案

reactjs mongodb api next.js bcrypt
1个回答
0
投票

您的代码中有几个问题:

您使用

bcrypt
进行密码散列是异步的,但您在创建用户之前不需要等待生成散列。这可能会导致保存空的或不正确的
hashPassword
。将await 与bcrypt.hash 一起使用以确保您在继续之前获得哈希密码。

let hashPassword = await new Promise((resolve, reject) => {
  bcrypt.hash(password, 10, (err, hash) => {
    if (err) reject(err);
    resolve(hash);
  });
});

此外,catch 块中的

status
被错误地拼写为“stauts”。更正这一点以防止将来出现错误。

您错误地使用了

NextResponse.json
。第二个参数不是用于设置状态。更改您的响应格式以正确设置状态

return new Response(JSON.stringify({ message: "User registered." }), { status: 201 });

您的客户端代码不处理来自 API 的响应。这就是为什么您总是看到状态 200,因为 API 中未处理的错误可能不会按预期传播。添加响应处理以检查错误或成功注册。

const response = await fetch("api/register", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    name: name,
    email: email,
    password: password,
  }),
});
const data = await response.json();
if (response.status !== 201) {
  console.error('Registration failed:', data.message);
} else {
  console.log('Registration successful:', data.message);
}

确保检查客户端和服务器端控制台是否有任何错误。验证您的 MongoDB 连接是否已正确建立。确保客户端获取中的端点与实际的 API 路由匹配。

© www.soinside.com 2019 - 2024. All rights reserved.