admin管理员组文章数量:1301563
I am new to working with Postman, and I am working on learning the MERN tech stack, starting with this tutorial playlist (MERN Authentication System With Email Verification). I am on this video (Storing User With Hashed Password), and from what I can tell, my overall code is fine, but I may have a simple mistake somewhere. I have looked over other solutions for this problem, but none of them have helped. I have attached my code below.
Model
const mongoose = require("mongoose");
const bcrypt = require("bcrypt");
const userSchema = new mongoose.Schema({
name: {
type: String,
required: true,
},
email: {
type: String,
unique: true,
required: false,
},
password: {
type: String,
unique: true,
required: false,
},
});
userSchema.pre("save", async function (next) {
if (this.isModified("password")) {
const hash = await bcrypt.hash(this.password, 8);
this.password = hash;
}
next();
});
module.exports = mongoose.model("User", userSchema);
Controller / Create User Function
const User = require("../model/user");
exports.createUser = async (req, res) => {
const { name, email, password } = req.body;
const user = await User.findOne({ email });
if (user) {
return res
.status(400)
.json({ success: false, error: "This email is already registered" });
}
const newUser = new User({
name,
email,
password,
});
await newUser.save();
return res.send(newUser);
};
Validator Middleware
const { check, validationResult } = require("express-validator");
exports.validateUser = [
check("name")
.trim()
.not()
.isEmpty()
.withMessage("Name is required.")
.isLength({ max: 20 })
.withMessage("Name cannot be more than 20 characters."),
check("email").normalizeEmail().isEmail().withMessage("Invalid Email"),
check("password")
.trim()
.not()
.isEmpty()
.withMessage("Password is required.")
.isLength({ min: 8, max: 20 })
.withMessage("Minimum of 8 characters; Maximum of 20 characters"),
];
exports.validate = (req, res, next) => {
const error = validationResult(req).array();
if (!error.length) return next();
return res.status(400).json({ success: false, error: error[0].msg });
};
Here are the images of the smaller files:
- App.js
- Database Connection
- Create User Route
This is my result in Postman:
Result from Postman
It should be noted that [email protected] is not already saved in the database.
Finally, I am aware that I have an issue with semicolon consistency, and I am working on it. The same goes for making my code look cleaner.
Thank you for your help!
Edit: Woke up, and it worked. No changes to the code was made.
版权声明:本文标题:node.js - Postman 400 Bad Request Error: This request could not be fulfilled due to bad syntax - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741672962a2391713.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论