HTTP POST requests allow users to send data to the server. To send a POST request using the Express web framework in Node.js, use the app.post() method.
The app.post() method defines a route handler for HTTP POST requests. It specifies the endpoint URL and callback function to execute when a POST request is received.
Syntax
app.post(path, callback)
Parameters
Name | Description |
path | It is an endpoint URL where the POST route is accessible. |
callback | It is a function that will be executed when the endpoint is executed via a POST request.
The function takes two arguments:
|
Setting up the express server
To set up an express server, you need to install the express first:
npm install express
Also, install the dotenv module to add environment variables for the sensitive data like port number:
npm install dotenv
Create a .env file inside the root folder and define the port in it:
PORT=4000
To use ES Modules, you need to add type:module in the package.json file like this:
{ "type": "module" }
Now, you can use the “import” instead of “require”.
Create a file called app.js inside the root of your project directory and add the below code:
// Import the necessary modules using ES module syntax import express from 'express'; // Import the env variables from '.env' file import { config } from 'dotenv'; // Load environment variables from .env file config(); // Create an instance of the Express application const app = express(); // Define the port number const port = process.env.PORT; // Middleware to parse JSON bodies app.use(express.json()); // Define a POST route app.post('/user/store/', (req, res) => { try { // Extract data from the request body const { name, email } = req.body; if (!name || !email) { return res.status(400).json({ message: 'Name and email are required' }); } // For demonstration, we'll just log the data and send a response console.log(`Received data: Name - ${name}, Email - ${email}`); // Send a response back to the client res.status(200).json({ message: 'Data received successfully', data: req.body }); } catch (error) { // Handle errors console.error('Error processing request:', error); res.status(500).json({ message: 'Internal Server Error' }); } }); // Start the server app.listen(port, () => { console.log(`Server is running on http://localhost:${port}`); });
We first imported express and environment variables (by loading config) for our application. Then, we defined a PORT by referencing the environment variable from the .env file.
We defined middleware to parse json bodies coming from a request.
In the next step, we defined a post route using the app.post() method, which has the URL http://localhost:4000/user/store and accepts a callback function with req and res arguments.
We wrapped the callback function with a try-catch block to catch potential errors. This makes the code more resilient to errors. If something goes wrong, it will return a 500 Internal server error.
Save this app.js file, go to the terminal (cmd), and start the server using this command:
node app
It will boot up the Node.js web server.
Test our endpoint
We can use the POSTMAN client to test the endpoint and send a POST request.
Send a POST request to http://localhost:3000/user/store with a JSON body containing the data.
Open the POSTMAN, construct a POST request, and enter the Request URL.
Click the “Body” tab below the URL field to set the request body. Select the “raw” option. From the dropdown next to the “raw” option, select JSON.
If you send a POST request by configuring the above setting to the Node.js server, you will get a response like this:
If you see the terminal, we log the request like this:
Following these steps, you can easily send a POST request using Postman.
Hashim Warren
thanks for this. How do you send a POST request from an HTML form?