在expressjs4.x中req.body undefined

时间:2016-04-30 15:04:33

标签: node.js express

我已经仔细阅读了关于此的所有答案,但似乎没有任何效果。

这是我的app.js

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

var about = require('./routes/about');

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: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/about', about);

// 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.locals.pretty = true;
  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;

这是我的about.js

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

router.get('/', function(req, res) {
    res.render('about');    
});

router.post('/', function(req, res) {
    console.log("Called");
    console.log(req.body); // this is always undefined

    //below variables are also undefined
var name = req.body.contactName, 
        email = req.body.contactEmail,
        message = req.body.contactMessage,
        subj = req.body.contactSub;

});


module.exports = router;

我已经花了相当多的时间来处理app.js文件中的声明,正如许多SO答案所建议的那样,但我想我已经幸运了。我当然做错了但却无法找到它。请注意,我是nodejs世界的相对初学者。

以下是req.headers

{ host: 'debian:3000',
  connection: 'keep-alive',
  'content-length': '0',
  'cache-control': 'max-age=0',
  accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
  origin: 'http://debian:3000',
  'upgrade-insecure-requests': '1',
  'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.112 Safari/537.36',
  'content-type': 'application/x-www-form-urlencoded',
  referer: 'http://debian:3000/about',
  'accept-encoding': 'gzip, deflate',
  'accept-language': 'en-US,en;q=0.8' }

更新 我错过了在表单中添加name,这导致了这个问题。感谢@ t.niese建议。

1 个答案:

答案 0 :(得分:1)

content-length标头的值为0的情况告诉您客户端未在请求正文中发送任何数据。因此,您需要在客户端查找问题,因为您希望正文中有一些数据。

它可能有不同的原因 - 并且在评论中这实际上是问题 - 是你忘了给表单元素一个名字。