#node.js #mongodb #express #mongoose #mongoose-schema
#node.js #mongodb #экспресс #mongoose #mongoose-схема
Вопрос:
Я новичок в mongoose и express. Я пытаюсь создать простой сервер входа в систему, однако при отправке запроса post с
{ «userEmail»: «abc @xyz», «пароль»: «pswrd» }
Я получаю ошибку «электронная почта не определена», тип которой — «ПРОВЕРКА». Моя схема пользователя выглядит следующим образом:
const mongoose = require("mongoose");
const bcrypt = require("bcrypt");
const UserSchema = new mongoose.Schema({
email: {
type: String,
required: [true, "Email is required"],
trim: true,
unique: true,
},
password: {
type: String,
trim: true,
required: [true, "Password is required"],
},
username: {
type: String,
required: [true, "Username is required"],
trim: true,
unique: true,
},
});
UserSchema.pre("save", async function (next) {
const user = await User.findOne({ email: this.email });
if (user) {
next(new Error(`${this.email} already taken`));
return;
}
const user1 = await User.findOne({ username: this.username });
if (user1) {
next(new Error(`${this.username} already taken`));
return;
}
const salt = await bcrypt.genSalt(8);
this.password = await bcrypt.hash(this.password, salt);
next();
});
// userSchema.statics is accessible by model
UserSchema.statics.findByCredentials = async (email, password) => {
const user = await User.findOne({ email });
if (!user) {
throw Error("User does not exist.");
}
const isMatch = await bcrypt.compare(password, user.password);
if (!isMatch) {
throw Error("Unable to login");
}
return user;
};
const User = mongoose.model("User", UserSchema);
module.exports = User;
Я использую findByCredentials, чтобы проверить, есть ли пользователь в моей базе данных MongoDB или нет. Наконец, мой login.js заключается в следующем:
const express = require("express");
const mongoose = require("mongoose");
const User = require("../db/models/User");
const loginRouter = express.Router();
loginRouter.get("/api/login2", (req, res) => res.send("In Login"));
loginRouter.post("/api/login", async (req, res) => {
const { userEmail, password} = req.body;
if (!validateReqBody(userEmail, password)) {
return res
.status(401)
.send({ status: false, type: "INVALID", error: "invalid request body" });
}
try {
const newUser = new User({
email: userEmail,
password: password,
});
await newUser.findByCredentials(email, password);
} catch (error) {
const validationErr = getErrors(error);
console.log(validationErr);
return res
.status(401)
.send({ status: false, type: "VALIDATION", error: validationErr });
}
res.send({ status: true });
});
//user.find --> mongoose documentation
// Validates request body
const validateReqBody = (...req) => {
for (r of req) {
if (!r || r.trim().length == 0) {
return false;
}
}
return true;
};
// Checks errors returning from DB
const getErrors = (error) => {
if (error instanceof mongoose.Error.ValidationError) {
let validationErr = "";
for (field in error.errors) {
validationErr = `${field} `;
}
return validationErr.substring(0, validationErr.length - 1);
}
return error.message;
};
module.exports = { loginRouter };
Спасибо.
Комментарии:
1. Распечатайте
req.body
значение, если оно пустое, вам нужно зарегистрироватьсяbody parse
.2. @hoangdv Привет, спасибо за ваш ответ. Я только что распечатал req.body, он не пустой, он такой же, как и при отправке запроса post.
Ответ №1:
Вам необходимо использовать промежуточное программное обеспечение для синтаксического анализа тела в серверной части
const bodyParser = require('body-parser');
const express = require('express');
const app = express();
//bodypraser middleware
app.use(bodyParser.json());
Вы можете прочитать больше о bodyparser здесь
Ответ №2:
Случилось со мной однажды, это было действительно раздражающе. Я не знаю, поможет ли вам это, но попробуйте отправить запрос post с headers: { 'Content-Type': 'application/json' },
помощью using fetch
.
Ответ №3:
Определение функции findByCredentials() находится в пользовательской модели. Я пытался получить доступ к этой функции с помощью экземпляра объекта newUser, который я создал в login.js . Однако я должен был вызвать функцию как User.findByCredentials(адрес электронной почты, пароль).