作为初学者我试图在节点js中使用express来开发一个非常简单的服务我的服务的目标是获取一个值的简单索引页面,并在提交后显示在下一页。这是app.js中的我的代码。我无法通过req.body获得文本框的值。当我在控制台中打印req.body.response时显示未定义。任何帮助将不胜感激。
var http = require('http'); //used for http request
var express = require('express'); //express
var session = require('express-session'); //used for creating session
var bodyParser = require('body-parser');
var errorHandler = require('errorhandler'); //used for error handling
var cookieParser = require('cookie-parser'); //used for creation of cookies
var MongoStore = require('connect-mongo')(session); //mongo
var path = require('path');
var app = express();
app.set('views/index', path.join(__dirname, 'views/index'));
app.set('view engine', 'jade');
app.set('port', process.env.PORT || 3000);
app.use(cookieParser());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// build mongo database connection url //
var dbHost = process.env.DB_HOST || 'localhost'
var dbPort = process.env.DB_PORT || 27017;
var dbName = process.env.DB_NAME || 'demo';
var dbURL = 'mongodb://'+dbHost+':'+dbPort+'/'+dbName;
var data = '';
var response;
app.get('/', function(req, res) {
console.log(req.body.title);
response = {
email:req.body.email,
password:req.body.password
};
console.log(response);
res.render('index', { title: 'index' });
});
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
// jade的代码
doctype html
html
head
title home
body
form(method='get')
.col-lg-12
.col-lg-6
label name
.col-lg-6
input(type='text', name='name')
.col-lg-12
.col-lg-6
label email
.col-lg-6
input(type='email', name='email')
.col-lg-12
.col-lg-6
label Password
.col-lg-6
input(type='password', name='password')
.col-lg-12
input(type='submit', name='submit', value='Save')
答案 0 :(得分:1)
要发送数据,您的表单需要POST
,而不是GET
。
doctype html
html
head
title home
body
form(method='post', action='/')
.col-lg-12
.col-lg-6
label name
.col-lg-6
input(type='text', name='name')
.col-lg-12
.col-lg-6
label email
.col-lg-6
input(type='email', name='email')
.col-lg-12
.col-lg-6
label Password
.col-lg-6
input(type='password', name='password')
.col-lg-12
input(type='submit', name='submit', value='Save')
然后,您的应用程序中会出现req.body.name
,req.body.email
和req.body.password
。您没有提交任何名为title
的内容,因此req.body.title = undefined
。
答案 1 :(得分:1)