Jude Calimbas Jude Calimbas - 4 months ago 8
Javascript Question

how to get data passed from a form in Express (Node.js)

I would like to get data that are passed from a page using a form and use that data in the page that is redirected.



I have this form in my client side.

<form action="game" method="get">
<input type="text" name="name"/>
<input type="submit" />
</form>


and i have this script in my server.

app.get('/game',function(req,res){
res.sendfile(__dirname + '/game.html');
});


plss help.

Answer

To allow express to handle form data nicely you need to ensure you have bodyParser included like so:

var express = require('express'),
    app = express.createServer();

app.use(express.bodyParser());
//the rest of your configuration

Then in your POST handler you can access the form body through the Request.body property like so:

app.post('/game', function (req, res) {
    res.render('some-file', { name: req.body.name });
});

Also you'll need to use a templating engine (such as Jade) if you're intending to output the form data in the response.