Node.js 邮递员;错误:ValidationError:用户名:路径'username'是必需的;
我正试图用邮递员来测试我的路线。 下面是我的user.model.js文件Node.js 邮递员;错误:ValidationError:用户名:路径'username'是必需的;,node.js,mongodb,mongoose,postman,Node.js,Mongodb,Mongoose,Postman,我正试图用邮递员来测试我的路线。 下面是我的user.model.js文件 const mongoose = require('mongoose'); const Schema = mongoose.Schema; const userSchema = new Schema({ username: { type: String, required: true, unique: true, trim: true, minlength: 3 },
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const userSchema = new Schema({
username: {
type: String,
required: true,
unique: true,
trim: true,
minlength: 3
},
}, {
timestamps: true,
});
const User = mongoose.model('User', userSchema);
module.exports = User;
下面是我的用户路由器文件
const router = require('express').Router();
let User = require('../models/user.model');
router.route('/').get((req, res) => {
User.find()
.then(users => res.json(users))
.catch(error => res.status(400).json('Error: ' + error));
});
router.route('/add').post((req, res) => {
const username = req.body.username;
const newUser = new User({ username });
newUser.save()
.then(() => res.json('User added!'))
.catch(error => res.status(400).json('Error: ' + error));
});
module.exports = router;
每次尝试为用户测试post路由时,我都会收到“错误:ValidationError:username:Pathusername
是必需的。”错误
下面是我的邮递员的截图
有谁能帮我找出我错在哪里。更换/添加路由器: const newUser=新用户({username:username});//改变
您必须以这种方式传递用户名。希望这对您有所帮助。如果您有任何错误,请告诉我。您传递的数据应为JSON格式,而不是多部分格式。更改您的邮递员请求如下并检查
我也有同样的问题。我可以通过在程序中添加以下部分来解决问题:
const bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
我的bodyparser版本是“^1.15.2”@Prakesh Karena如果我将从用户名字段中删除必需的属性,那么我可以将我的信息发布到我的路由。是否检查数据库存储用户名?是否在路由器中获取req.body.username?通过添加如下标题,它可以工作。单击Postman中的Headers按钮,并将值内容类型设置为application/json