I have been struggling to send data via a POST request to the register API, but for some reason, the data is not being transmitted. I have tried adjusting the settings on Postman, tinkering with validation rules, and various other troubleshooting steps, yet none of them seem to work.
Below you can find my register API code snippet:
app.use(express.json()); // This is a middleware function
app.post("/register", async (req, res) => {
try {
const newUser = await User.create(req.body);
res.status(200).json(newUser);
} catch (error) {
res.status(500).json({ message: error.message });
}
});
This is my user model:
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 in 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 header details:
...
Postman request body:
{...}
Response from the server:
{...}
Despite trying all possible solutions, nothing seems to be working. As someone relatively new to JavaScript, any help or guidance would be greatly appreciated.