问题陈述:当我运行node.js时出现错误
错误:大多数中间件(如bodyParser)不再与Express捆绑在一起,必须单独安装。请参阅https://github.com/
预期结果:应显示页面,用户可以将数据插入数据库。
这是我的代码:
filter.js
var express = require('express'),
http = require('http'),
fs = require('fs'),
bodyParser = require('body-parser'),
io = require('socket.io'),
filter = express();
mongoose = require('mongoose');
//all environments
filter.set('port', process.env.PORT || 3000);
filter.set('views', __dirname + '/views');
filter.set('view engine', 'jade');
filter.use(express.bodyParser());
filter.use(express.methodOverride());
//filter.use(filter.router);
filter.use(express.static(path.join(__dirname,'public')));
mongoose.connect('mongodb://localhost/Company');
var Schema = new mongoose.Schema({
_emailid: String,
name: String,
age: Number
});
var user = mongoose.model('emp', Schema);
filter.get('/view', function(req, res){
user.find({}, function(err, docs){
if(err) res.json(err);
})
});
filter.post('/new', function(res, req){
new user({
_emailid:req.body.email,
name:req.body.name,
age:req.body.age,
}).save(function(err, doc){
if(err) res.json(err);
else res.redirect('/view');
});
});
var server = http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port' + app.get('port'));
});
这是我的HTML代码:
<html>
<head>
<title>Please enter your details</title>
</head>
<body>
<h3>Please enter your details</h3>
<p>Please register below!!!</p>
<form action="/new" method="POST">
<label for="email">Email: </label>
<input type="email" name="email" /><br>
<label for="name">Name: </label>
<input type="text" name="name" /><br>
<label for="age">Age: </label>
<input type="number" name="age" /><t>
<input type="number" name="age" /><br>
<input type="submit" />
</form>
</body>
</html>
答案 0 :(得分:4)
快递4.x有很多变化。就像错误所说的那样,所有的中间件都被删除了。
更新您的package.json以包含&#34; new&#34;包,可在此处找到基本列表和完整列表https://github.com/expressjs
基本上你需要编辑
filter.use(express.bodyParser());
并替换为,
filter.use(bodyParser());
您还必须为methodOverride中间件执行此操作。
确保所有模块都已打包。
希望这会对你有所帮助,
var express = require('express'),
http = require('http'),
fs = require('fs'),
bodyParser = require('body-parser'),
methodOverride=require('method-override'),
io = require('socket.io'),
filter = express();
mongoose = require('mongoose');
//all environments
filter.set('port', process.env.PORT || 3000);
filter.set('views', __dirname + '/views');
filter.set('view engine', 'jade');
filter.use(bodyParser());
filter.use(methodOverride());
//filter.use(filter.router);
filter.use(express.static(path.join(__dirname,'public')));