0
我已經看過所有關於這個問題的答案,但似乎沒有任何工作。req.body undefined in expressjs4.x
這裏是我的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提出這個建議。
您正在顯示標題,但在哪裏做你的文章? –
你的代碼看起來很好,但請求的'content-length'是'0',你確定你的表單中有任何命名的輸入元素嗎?你可以使用'curl -i -d「param1 = value1&param2 = value2」http:// localhost:3000/about「直接測試你的代碼,並檢查控制檯是否正確輸出params參數。{{param1:'value1',param2: 'value2'}'。 –
請使用提交給您的路由器的表單發佈您的視圖。 – roflmyeggo