Jude Calimbas Jude Calimbas - 1 year ago 76
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" />

and i have this script in my server.

res.sendfile(__dirname + '/game.html');

plss help.

Answer Source

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();

//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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download