大家好,我是MEAN Stack的新手,我正尝试使用Postman发出发布请求,但会引发未定义的错误用户名。.与mongodb的连接已成功完成,并且工作正常,但会提示用户未定义的标识符用户名.username我无法调试该错误。我也尝试使用浏览器引发发布请求,但没有帮助。
代码:
user.js
var mongoose = require('mongoose');
var schema = mongoose.Schema;
var UserSchema = new schema({
username : {type:String,lowercase:true,required:true,unique:true},
password : {type:String,required:true},
email : {type:String,required:true,unique:true}
});
module.exports = mongoose.model('User',UserSchema);
index.js(server.js)
//Variables------------------------------
var express = require('express');
var app = express();
var port = process.env.PORT || 8080;
var morgan = require('morgan');
var mongoose = require('mongoose');
var User = require('./app/models/user');
var bodyParser = require('body-parser');
//---------------------------------------
//Configuration--------------------------
app.use(bodyParser.urlencoded({ extended: true })); // for parsing
application/x-www-form-
app.use(bodyParser.json()); // for parsing application/json
app.use(morgan('dev'));
mongoose.connect('mongodb://localhost:27017/development',function(err){
if(err){
console.log('Not connected '+err);
}else{
console.log('Connected to db');
}
});
//----------------------------------------
//Routes----------------------------
app.get('/', function(req, res) {
res.send('Hello World with a post number'+port);
});
app.get('/home',function(req,res){
res.send('Hello from home');
});
app.post('/users',function(req,res){
var user = new User();
//res.send('This is working'+user);
user.username=req.body.username;
user.password=req.body.password;
user.email =req.body.email;
//user.save()
res.send("username "+user.username);
res.send("password"+user.password);
res.send("email"+user.email);
res.send('User Registered!!!');
});
//-----------------------------------
app.listen(port,function(){
console.log('Running the server');
});
答案 0 :(得分:1)
定义了“用户”的更新代码
var user = new User({
username: req.body.username,
password: req.body.password,
email: req.body.email,
});
在req.body.email
之后应该没有逗号。
您还应该得到错误:
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
在控制台中,因为您在res.send
中有多行app.post()
;只能使用一个。
如Sandeep所述,请不要忘记取消评论user.save()
。
我用您的代码进行了此操作,从三个输入字段中提交了文本,并能够在我的集合“用户”中获取文档。
答案 1 :(得分:0)
var user = new User({
username: req.body.username,
password: req.body.password,
email: req.body.email,
});
这将为您工作。