Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
132 views
in Technique[技术] by (71.8m points)

javascript - 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'); 
});
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...