The express.urlencoded() function is a built-in middleware function in Express. It parses incoming requests with URL-encoded payloads and is based on a body parser.
Syntax:
express.urlencoded( [options] )
Parameter: The options parameter contains various properties like extended, inflate, limit, verify, etc.
Return Value: It returns an Object.
Steps to create the application:
Step 1: You can install this package by using this command.
npm install express
Step 2: After installing the express module, you can check your express version in the command prompt using the command.
npm version express
Project Structure:
The updated dependencies in package.json file will look like:
"dependencies": {
"express": "^4.18.2",
}
Example 1: Below is the code example for express.urlencoded() Function
const express = require( 'express' );
const app = express(); const PORT = 3000; app.use(express.urlencoded({ extended: false }));
app.post( '/' , function (req, res) {
console.log(req.body);
res.end();
}); app.listen(PORT, function (err) {
if (err) console.log(err);
console.log( "Server listening on PORT" , PORT);
}); |
Steps to run the program:
Run the index.js file using the below command:
node index.js
Console Output:
Server listening on PORT 3000
Browser Output: Now make a POST request to http://localhost:3000/ with header set to ‘content-type: application/x-www-form-urlencoded’ and body {“name”:”GeeksforGeeks”}, then you will see the following output on your console:
const express = require( 'express' );
const app = express(); const PORT = 3000; // Without this middleware // app.use(express.urlencoded({extended:false})); app.post( '/' , function (req, res) {
console.log(req.body);
res.end();
}); app.listen(PORT, function (err) {
if (err) console.log(err);
console.log( "Server listening on PORT" , PORT);
}); |
Steps to run the program:
node index.js
Now make a POST request to http://localhost:3000/ with header set to ‘content-type: application/x-www-form-urlencoded’ and body {“title”:”GeeksforGeeks”}, then you will see the following output on your console:
Output:
Server listening on PORT 3000
undefined
We have a complete list of Express express module methods, to check those please go through this Express.js express() function Complete Reference article.