Reputation: 21
I'm using node with [email protected] and [email protected].
My jade page has for instance this property:
input(type='text',class='form-control', placeholder="Username", name='username', id="username")
The JavaScript code looks like this:
var bodyParser = require('body-parser');
var express = require('express')
, routes = require('./routes')
, user = require('./routes/user')
, http = require('http')
, path = require('path');
var app = express();
var favicon = require('favicon')
app.use(bodyParser.json());
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use( function(req, res, next){
app.locals.pretty = true
next()
});
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(express.static(path.join(__dirname, 'public')));
app.get('/create', function(req,res) {
res.render("create");
});
app.get('/creation', function(req,res) {
console.log("creation")
console.log(req.body)
});
The create page is the first opened and there is also the input field username, but the request body is empty in the /creation function. Can anyone help ?
Upvotes: 0
Views: 855
Reputation: 215
As we understood body parse will work on the submit of the form or json with POST request. in this case make sure you are submitting the form correctly, you can see the POST request in firebug or other tool. Once its done correctly you will be able to see the body elements by req.body.username
you can have simple form like.
<form action='post' ..>
<input name='username' ..>
<input type='submit' ..>
</form>
Also I seen two times middleware app.use(bodyParser.json()); use. in case you missed it.
Upvotes: 0
Reputation: 4783
You need to submit the form using POST method and alter the function:
app.post('/creation', function(req,res) {
console.log("creation")
console.log(req.body); // here will show the values of inputs submited
});
Upvotes: 1