router.post

The router.post is the method that is used to define the route for handling the HTTP POST request on the specified path. Here the post method is linked with creating or submitting the data to the server and it also takes the callback function as its second argument which specifies the logic to be executed when the POST request is done on the route.

Syntax:

router.post('/example', (req, res) => {
// handle the POST request
res.send('Handling POST request');
});

Project Structure:

Example: In the below example, we have set up a simple Express server that listens for the POST request on the /api/example route and responds with he JSON message when the request is been handled.

Javascript




//app.js
 
const express = require('express');
const app = express();
const port = 3000;
// middleware to parse JSON in requests
app.use(express.json());
// define a route that handles POST requests
app.post('/api/example', (req, res) => {
    const data = req.body;
    res.json({ message: 'Hey Geek! POST request received', data });
});
// start the server
app.listen(port, () => {
    console.log(`Server is listening on port ${port}`);
});


Output:

What is the difference between export.create and router.post?

export.create and router.post are used in the context of backend frameworks like Express JS. They both are used for handling HTTP requests and operate at different levels within the framework. In this article we will learn about export.create and router.post and see the key differences between them.

Similar Reads

Prerequisites

Node JS Express JS Postman...

Steps to Create Express JS Application

Step 1: In the first step, we will create the new folder by using the below command in the VScode terminal....

export.create

In Web Programming the export.create is used for making a function, variable, or module available for use in other parts of the program. Using this, we can properly modularize the code by exporting a specific function that is responsible for creating or initializing the objects....

router.post

...

Difference between export.create and router.post

...

Conclusion:

The router.post is the method that is used to define the route for handling the HTTP POST request on the specified path. Here the post method is linked with creating or submitting the data to the server and it also takes the callback function as its second argument which specifies the logic to be executed when the POST request is done on the route....

Contact Us