如何使用 Express (Node.js)从表单获取数据

我希望获取使用表单从页面传递的数据,并在被重定向的页面中使用这些数据。

我的客户端有这个表格:

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

我的服务器上有这个脚本:

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

IMPORTANT: This is deprecated, the accepted answer is the correct solution.


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.

If you need to access variable names in your views, you should use the res.render function and pass the variable like:

res.render('game', {
name: req.body.name
}

and then in jade do

div!= name

Use bodyParser.urlencoded() middleware:

const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));

Then the form values will be on req.body:

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

Setting { extended: true } allows the bodyParser to accept json like data within the form data including nested objects. e.g. { person: { name: Adam } } sent using javascript rather than the name value pairs which traditional HTML form send. If you don't need that you can set the extended value to false. Not defining an extended option (i.e. using a default setting) is apparently deprecated and they seem to want you to decide whether you need nested options or plain name value pairs.

If you want to be able to parse form data for some routes and json data for others in your express server, you can use:

app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: <true|false> }))

urlencoded() for x-www-form-urlencoded content type

  • true - for nested data structures
  • false - for name value pairs

json() - for application/json content type

Note that form/multipart needs a different body parser (such as multer)

Update: fix if you get ExpressJS Error about Body-Parser being Deprecated

Replace

app.use(bodyparser.json()); //utilizes the body-parser package
app.use(bodyParser.urlencoded({extended: true}));

By

app.use(express.json()); // Used to parse JSON bodies
app.use(express.urlencoded()); //Parse URL-encoded bodies

or you can simply use express to do so:

   const express = require('express')
const app = express()


app.use(express.json()) // for json
app.use(express.urlencoded({ extended: true })) // for form data