In this tutorial, you will learn how to post and get form-data from Postman in node js express js applications.
How to Get Form Data from Postman in Node.js Express
Steps to get or post form data from Postman and handle form body requests in applications:
Step 1: Set up a Node.js Express Application
If you haven’t already created a Node.js Express application, then you can do it by running the following command on cmd or terminal:
mkdir express-form-data
cd express-form-data
Initialize a new Node.js project and install some required modules by running the following command on terminal or cmd:
npm init -y
npm install express --save
Step 2: Create an App.js File
Open your node js express project in any text editor and create a JavaScript file (e.g., app.js
) for node js Express application root directory:
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const port = 3000;
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.get('/', (req, res) => {
res.send('Welcome to the Express Form Data Tutorial!');
});
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
Next, run the following command on cmd or terminal to start your Node.js Express server:
node app.js
Your Express application is now running on http://localhost:3000
.
Step 3: Create a Route to Handle POST Form Data
Let’s create a route to handle form data sent from Postman. Add the following code below your existing app.
js file:
app.post('/submit-form', (req, res) => {
const formData = req.body;
res.json(formData);
});
Step 4: Post Form Data with POSTMAN
To post form data in node Express js server:
- Open Postman and create a new request.
- Set the request method to
POST
. - Enter the URL for your Express application, which should be
http://localhost:3000/submit-form
. - In the “Body” tab, select “x-www-form-urlencoded” as the data type.
- Add some form data by clicking the “Add Row” button. You can create key-value pairs, where the key represents the form field name and the value represents the data.
- Click the “Send” button to send the POST request.
Conclusion
That’s it! You’ve successfully set up a Node.js Express application to handle GET or POST form data from Postman.