Express express.urlencoded() Function
Last Updated :
08 Jan, 2024
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
javascript
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:Â
Example 2: Below is the code example for express.urlencoded() Function
javascript
const express = require( 'express' );
const app = express();
const PORT = 3000;
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.
Share your thoughts in the comments
Please Login to comment...