【发布时间】:2020-02-28 11:10:27
【问题描述】:
我正在尝试使用邮递员测试我的路线。 以下是我的 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
},
}, {
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;
每次我尝试为用户测试发布路线时,我都会收到“错误:ValidationError:用户名:路径username 是必需的。”错误
下面是我邮递员的截图
谁能帮我弄清楚我错在哪里。
【问题讨论】:
-
你的路由器里有 req.body.username 吗?
-
通过添加如下标题,它可以工作。点击 Postman 中的 Headers 按钮并输入值 Content-Type application/json
标签: node.js mongodb mongoose postman