Express.js request.body not working

时间:2017-01-04 16:46:35

标签: node.js express body-parser

我有一个简单的登录表单,问题是当我按下"提交"时,服务器端的request.body是空的。我看到bodyParser是一个基本部分,但在我的情况下它&# 39; s在路线之前宣布,所以我认为问题是另一个。这是我的服务器页面 App.js

var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var index = 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');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', index);
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 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');
});
app.listen(3000);
module.exports = app;

这是 index.js

var express = require('express');
var router = express.Router();


function Login(req, res){
 var mongoClient = require('mongodb').MongoClient;
 mongoClient.connect('mongodb://localhost:27017/squaredDB', function(err, db)  {
 if(err) throw err;
  db.collection('users').find({email: req.body.email}, function(err, data){
   console.log(req.body);
  });
 });
}


 /* GET home page. */
 router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
 });

 router.post('/', function(req, res, next) {
  Login(req, res);
  res.render('app-home', { title: '' });
 });

 module.exports = router;

这是我的玉模板形式:

form(method="post" action="/")
  label Email
  input(type="text" placeholder="Email")
  label Password
  input(type="password" placeholder="Password")
  input(type="submit" value="login")

2 个答案:

答案 0 :(得分:2)

您在模板中缺少输入字段的name属性。没有这些,浏览器就不会在表单中提交它们。

答案 1 :(得分:1)

在输入字段中添加名称属性,现在可以通过 req.body.name

等请求访问该字段
<form action="/", method="POST">
    <input type="text" placeholder="name" name="name">
    <button type="submit">Submit</button>
</form>