Reputation: 507
Being a beginner i m trying to develop a very simple service using express in node js the aim of my service is that a simple index page taking a value and after submit it show on next page.This is mine code in app.js. i am not able to get value of text box by req.body. when i print req.body.response in console is shows undefined.any help will be appreciated.
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'));
});
//code for 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')
Upvotes: 2
Views: 2981
Reputation: 3475
Please check express docs:
If you submit your data via GET Query string, then express will provide those parameters already parsed as properties of the req.query
object, not req.body
Upvotes: 1
Reputation: 1294
In order to send data, your form needs to POST
, not 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')
You will then have req.body.name
, req.body.email
and req.body.password
available in your application. You are not submitting anything called title
, hence req.body.title = undefined
.
Upvotes: 1