几天后我就遇到麻烦了。我正在学习平均堆栈,但是在使用mongoose模式在mongo上创建用户时,我遇到了以下问题:
(节点:93337) UnhandledPromiseRejectionWarning: ValidationError:用户验证失败:用户名:路径
username是必需的。密码:路径password是必需的。电子邮件:路径
这是我的密码:
服务器部分:
mongoose.connect('mongodb://localhost:27017/Wisebatt', err => {
if (err) {
console.log(`Not connected to db ${err}`)
} else {
console.log('Successfully connected to db')
}
})..。
app.post('/register', (req, res) => {
const user = new User();
user.username = req.body.username;
user.password = req.body.password;
user.email = req.body.email;
user.save();
res.send('User created');
});UserSchema:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const UserSchema = new Schema({
username: { type: String, required: true, unique: true},
password: { type: String, required: true },
email: { type: String, required: true, unique: true},
});
module.exports = mongoose.model('User', UserSchema);以下是我正在使用的附加组件:
发布于 2018-05-27 02:46:14
好吧我发现了问题..。
显然,这一问题是由以下两种之一造成的:
令人惊讶的是,我和邮递员试过了,这个请求成功了。所以所有的代码都很好,问题来自两个中的一个。
这让我学到了一件事。如果不是你的代码,那就是你所使用的软件可以摧毁你所做的一切
发布于 2018-05-27 01:59:23
尝试在您的路线之前将其添加到您的快速代码中。这是一个中间件,当您向后端发送请求时,它将设置req.body对象。(您还需要安装npm -保存正文解析器)
const bodyParser = require('body-parser')
app.use(bodyParser.urlencoded({ extended: true }))
app.use(bodyParser.json())如果你在使用rest客户端。确保您有一个请求头,如:
Content-Type: application/x-www-form-urlencoded发布于 2018-09-06 13:55:33
如果您使用的是expressJS,那么请确保必须添加这一行。
const express = require('express');
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: true }));特别是这个,
app.use(express.urlencoded({ extended: true }));这实际上解决了我的问题。
https://stackoverflow.com/questions/50548404
复制相似问题