How to get Post Data in Node.js ?
POST is a request method supported by HTTP that sends data to the server. In express, we can use the app.post() method to accept a POST request. The basic syntax to use the app.post() method is mentioned below.
The post data is provided to us on the req object inside the callback function of the app.post() method. We can access the data sent as the body using the syntax mentioned below.
const bodyContent = req.body;
Similarly, if we want to access the header content then we can do so using the syntax mentioned below.
const headerContent = req.headers;
Step 1: Install Node.js if Node.js is not installed in your machine.
Step 2: Create a folder for your project and created two files named app.js and index.html inside of it.
Step 3: Now, initialize a new Node.js project with default configurations using the following command on the command line.
npm init -y
Step 4: Now install express inside your project using the following command on the command line.
npm install express
Project Structure: After following the steps your project structure will look like.
In the above example, we have created an express server that renders the index.html file. This index.html contains a form that has two inputs as username and password. When we press the submit button it sends a POST request to the home route with the body containing the username and password and the header containing the authorization token. We handle this post request inside our app.post() method and send these details i.e., the username, password, and authorization token as a response. We later print these details to the console.
Run app.js file using below command:
Output: Open the browser and go to http://localhost:3000 and you will see the following output.