express 4.2 现在无法在路由文件中获取 表单post过来的值,console.log(req.body) 为 undefined 。 求大神支招。
express 4.x版本中已经将bodyParser中间件分离了,需要单独安装模块,就可以对post进行解析了。 貌似默认依赖了bodyParser ,可以用来解析常规的表单提交。但是文件上传的话需要另外安装模块 官方推介的模块:connect-multiparty github地址:https://github.com/andrewrk/connect-multiparty
示例:
在app.js 中使用
var xxx = require(); 引入处理模块
app.post('/xx’,xxx); 路由控制
将下面的内容放在你具体解析,操作post的模块中
var multipart = require(‘connect-multiparty’); //在处理模块中引入第三方解析模块
var multipartMiddleware = multipart();
app.post('/upload’, multipartMiddleware, function(req, resp) {
console.log(req.body, req.files);
// don’t forget to delete all req.files when done
});
不明白的可以继续探讨
bodyParser 这个组件 我已经安装了,然后app.js 中也use了 。 我现在还不需要文件上传 所以那个没安装。 但是我现在还是不能获取 req.body 的值 ,仍然是undefined 。 感觉很怪。
login表单
<form action="/login" method="post"> <input type="text" name="user"/> <input type="password" name="pwd"/> <input type="submit" value="Submit"/> </form>在app.js里面加上: app.use('/login’,function(req,res){ console.log(req.body.user); console.log(req.body.pwd); });
演示截图如下: 不能粘贴图片 控制台输出: admin 123456 POST /login 200 13ms 你要的就是解析出这个数据吧?
app.use(logger(‘dev’)); app.use(bodyParser.json()); app.use(bodyParser.urlencoded());
req.body 就是接收的JSON
嗯,这几个组件我都有 app.use(bodyParser.json()); app.use(bodyParser.urlencoded()); 这两行代码 我也有 , 但是 req.body 还是 { }。
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
我的是这样写的,其中bodyParser 已经从express中分离而来需要单独安装下 我的express版本号是4.5.0 bodyParser 1.5.0
请参考我的文章“使用express4.x版和Jade模板重写《nodejs开发指南》微博实例”, 网址:http://cnodejs.org/topic/53f23e198f44dfa35129c43b
app.js的代码:
var express = require(‘express’); var path = require(‘path’); var favicon = require(‘static-favicon’); var logger = require(‘morgan’); var cookieParser = require(‘cookie-parser’); var bodyParser = require(‘body-parser’); //var partials = require(‘express-partials’);用jade模板,不能使用这个中间件 var session = require(‘express-session’); var MongoStore = require(‘connect-mongo’)(session); var settings = require(‘./settings’); var flash = require(‘connect-flash’); var routes = require(‘./routes/index’); var users = require(‘./routes/users’);
var app = express();
// view engine setup app.set('views’, path.join(__dirname, ‘views’)); app.set('view engine’, ‘jade’); //app.use(partials());
app.use(favicon()); app.use(logger(‘dev’)); app.use(bodyParser.json()); app.use(bodyParser.urlencoded());
//cookie解析的中间件 app.use(cookieParser()); app.use(express.static(path.join(__dirname, ‘public’))); app.use(flash());
//提供session支持 app.use(session({ secret: settings.cookieSecret, store: new MongoStore({ db: settings.db, }) }));
app.use(function(req, res, next){ console.log(“app.usr local”); res.locals.user = req.session.user; res.locals.post = req.session.post; var error = req.flash(‘error’); res.locals.error = error.length ? error : null;
var success = req.flash(‘success’); res.locals.success = success.length ? success : null; next(); });
app.use('/’, routes); app.use('/users’, users);
/// catch 404 and forward to error handler app.use(function(req, res, next) { var err = new Error(‘Not Found’); err.status = 404; next(err); });
/// error handlers
// development error handler // will print stacktrace if (app.get(‘env’) === ‘development’) { app.use(function(err, req, res, next) { res.status(err.status || 500); res.render('error’, { message: err.message, error: err }); }); }
// production error handler // no stacktraces leaked to user app.use(function(err, req, res, next) { res.status(err.status || 500); res.render('error’, { message: err.message, error: {} }); }); module.exports = app; index.js代码
var express = require(‘express’); var app = express(); var router = express.Router(); var crypto = require(‘crypto’); var User = require(‘…/models/user.js’); var Post = require(“…/models/post.js”); / GET home page. /
router.get('/’, function(req, res) { Post.get(null, function(err, posts) { if (err) { posts = []; } res.render('index’, { title: '首页’, posts: posts, user : req.session.user, success : req.flash(‘success’).toString(), error : req.flash(‘error’).toString() }); }); //res.render('index’, { title: ‘首页’ }); });
router.get("/reg", checkNotLogin); router.get("/reg",function(req,res) { res.render("reg",{ title : “用户注册” }); });
router.get("/login", checkNotLogin); router.get("/login",function(req,res) { res.render("login",{ title:"用户登录", }); });
router.get("/logout", checkLogin); router.get("/logout",function(req,res) { req.session.user = null; req.flash('success’, ‘退出成功’); res.redirect(‘/’); });
router.get("/user", function(req,res){ res.render("user",{ title: "用户页面", }); });
router.post("/login", checkNotLogin); router.post("/login",function(req,res) { var md5 = crypto.createHash(‘md5’); var password = md5.update(req.body.password).digest(‘base64’);
User.get(req.body.username, function(err, user) { if (!user) { req.flash('error’, ‘用户不存在’); return res.redirect(‘/login’); }
if (user.password != password) {
req.flash('error', '用户名或密码错误');
return res.redirect('/login');
}
req.session.user = user;
req.flash('success', req.session.user.name + '登录成功');
res.redirect('/');
});
});
router.post("/reg", checkNotLogin); router.post("/reg", function(req, res) { console.log(req.body[‘password’]); console.log(req.body[‘password-repeat’]); if(req.body[‘password-repeat’] != req.body[‘password’]){ req.flash('error’, ‘两次输入的密码不一致’); return res.redirect(‘/reg’); } var md5 = crypto.createHash(‘md5’); var password = md5.update(req.body.password).digest(‘base64’);
var newUser = new User({ name: req.body.username, password: password, }); //检查用户名是否已经存在 User.get(newUser.name, function(err, user) { if (user) { err = 'Username already exists.’; } if (err) { req.flash('error’, err); return res.redirect(‘/reg’); }
newUser.save(function(err) { if (err) { req.flash('error’, err); return res.redirect(‘/reg’); } req.session.user = newUser; req.flash(‘success’, req.session.user.name+’注册成功’); res.redirect(‘/’); });
}); });
function checkNotLogin(req, res, next) { if (req.session.user) { req.flash('error’, ‘用户已经登录’); return res.redirect(‘/’); } next(); } function checkLogin(req, res, next) { if (!req.session.user) { req.flash('error’, ‘用户尚未登录’); return res.redirect(‘/login’); } next(); }
router.post("/post",checkLogin); router.post("/post",function(req,res) { var currentUser = req.session.user; var post = new Post(currentUser.name, req.body.post); post.save(function(err) { if (err) { req.flash('error’, err); return res.redirect(‘/’); } req.flash('success’, ‘发表成功’); res.redirect(‘/u/’ + currentUser.name); }); });
router.get("/u/:user",function(req,res) { User.get(req.params.user, function(err, user) { if (!user) { req.flash('error’, ‘用户不存在’); return res.redirect(‘/’); } Post.get(user.name, function(err, posts) { if (err) { req.flash('error’, err); return res.redirect(‘/’); } res.render('user’, { title: user.name, posts: posts }); }); }); }); module.exports = router;