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'); });
To get started with forms, we will first install the body-parser(for parsing JSON and url-encoded data) and multer(for parsing multipart/form data) middleware. var express = require('express'); var bodyParser = require('body-parser'); var multer = require('multer'); var upload = multer(); var app = express(); app.
The method attribute specifies how to send form-data (the form-data is sent to the page specified in the action attribute). The form-data can be sent as URL variables (with method="get" ) or as HTTP post transaction (with method="post" ). Notes on GET: Appends form-data into the URL in name/value pairs.
Express has a built-in express. json() function that returns an Express middleware function that parses JSON HTTP request bodies into JavaScript objects. The json() middleware adds a body property to the Express request req . To access the parsed request body, use req.
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 structuresfalse
- for name value pairsjson()
- 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With