尽管一切正常,但是从POSTMAN获得成功消息后,我在node.js中收到此错误 抛出新的ERR_HTTP_HEADERS_SENT('set');
在我的mLab数据库上,也未创建集合名称用户。可能是由于上述错误所致。
解决这个问题会很有帮助。
这是我的app.js代码
var createError = require('http-errors');
var express = require('express');
var exphbs = require('express-handlebars');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var app = express();
var User = require('./models/user');
//Connecting Mongoose with MLab
mongoose.connect('mongodb://gkhabas:shopping1@ds143604.mlab.com:43604/eshop', {useNewUrlParser: true }, function(err){
if(err){
console.log(err);
}
else{
console.log('Connection is Successfull');
}
});
// view engine setup
app.engine('.hbs', exphbs({defaultLayout: 'layout', extname: '.hbs'}));
app.set('view engine', 'hbs');
//Adding body-parser middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.post('/create-user', function (req, res, next) {
var user = new User();
user.profile.name = req.body.name;
user.password = req.body.password;
user.email = req.body.email;
user.save(function(err){
if(err) next(err);
res.json('successfull');
});
});
app.use('/', indexRouter);
app.use('/users', usersRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;