无法通过 Postman 为注册API发送数据

jjhzyzn0  于 12个月前  发布在  Postman
关注(0)|答案(1)|浏览(120)

我试图发送数据通过注册API后.但数据没有发送。我不明白到底是什么问题。我也试着改变 Postman 的设置,但它没有工作。我还修改了验证规则,但也没有成功。
下面是我注册API代码

app.use(express.json()); // middleware

 app.post("/register", async (req, res) => {
    try {
      const newUser = await User.create(req.body);
      res.status(200).json(newUser); // Send the newly created user as a response
    } catch (error) {
      res.status(500).json({ message: error.message });
    }
  });

我的用户模型

const mongoose = require("mongoose");
const bcrypt = require("bcrypt");

const validateEmail = function (email) {
  const emailRegex = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
  return emailRegex.test(email);
};

const UserSchema = mongoose.Schema({
  name: {
    type: String,
    required: [true, "Please Enter Your Name"],
  },
  email: {
    type: String,
    required: [true, "Please Enter Your Email"],
    validate: {
      validator: validateEmail,
      message: "Please fill a valid email address",
    },
  },
  password: {
    type: String,
    required: [true, "Please Enter Your Password"],
  },
});

UserSchema.pre("save", async function (next) {
  try {
    const salt = await bcrypt.genSalt(10);
    const hashedPassword = await bcrypt.hash(this.password, salt);
    this.password = hashedPassword;
    next();
  } catch (error) {
    next(error);
  }
});

const User = mongoose.model("User", UserSchema);

module.exports = User;|

报头

Request Headers
Content-Type: application/json
User-Agent: PostmanRuntime/7.33.0
Accept: */*
Postman-Token: 5da77db1-867b-4919-a02d-c343704b6eb2
Host: localhost:3000
Accept-Encoding: gzip, deflate, br
Connection: keep-alive
Content-Length: 99
Request Body
{
    "name":"pratik",
    "email":"[email protected]",
    "password":"PratikZajam@1999"
}
Response Headers
X-Powered-By: Express
Content-Type: application/json; charset=utf-8
Content-Length: 136
ETag: W/"88-VEpd9WSTE7wFAEzw7xIMM06sJpo"
Date: Wed, 04 Oct 2023 09:55:22 GMT
Connection: keep-alive
Keep-Alive: timeout=5

Postman 请求

{
    "name":"pratik",
    "email":"[email protected]",
    "password":"PratikZajam@1999"
}

响应

{
    "message": "User validation failed: password: Please Enter Your Password, email: Please Enter Your Email, name: Please Enter Your Name"
}

postman
我几乎什么都试过了但是没有效果。我是一个JavaScript新手

wkyowqbh

wkyowqbh1#

如果您使用Express,

app.use(express.json())

或使用body-parser

相关问题