AppDividend
Latest Code Tutorials

Express Post Request: The Complete Guide

In the HTTP sense, we have two main ways to collect the user’s data via browser: GET and POST. When using Node.js as a server platform, we almost use express as our web framework. So when we are building applications using Express, we will need to get information from our users.

Express post request

To send a post request in the Node.js express framework, use the express.Router().route().post() method. Express post request query parameters are sent by HTTP clients by forms or performing an AJAX POST request to send the data to the node server.

We use the Express POST method to save the data into the database. So underneath, what happens is that when the user sends a POST request to the server, on the server-side, we receive the request and extract the data, process the data(validation), and save the data into the database.

We start our demo by installing express. But before that, let us create a project folder by the following command.

mkdir expresspost

Go into the project folder.

cd expresspost

Open the project inside VSCode.

code .

Step 1: Install Express.

Initialize the package.json file using the following command.

npm init

You can install express using NPM or Yarn. It does not matter here.

yarn add express

# or

npm install express --save

Also, install the nodemon server as a development dependency.

npm install nodemon --save-dev

# or

yarn add nodemon --dev

Now, create the HTTP server. Inside the root folder, create one file called server.js and add the following code inside it.

// server.js

const express = require('express');

const app = express();
const PORT = process.env.PORT || 3000

app.listen(PORT, () => {
  console.log('Server is running on PORT:',PORT);
});

Go to the terminal and hit the following command to start the nodemon server.

nodemon server

Express Post Request Example Tutorial

Step 2: Connect the Express app to the MongoDB database.

First, start the MongoDB server using the following command. Then, please install MongoDB if you have not installed it previously.

mongod

Now, inside the root of the project folder, create one file called db.js and add the following code to it.

// db.js

module.exports = {
  DB: 'mongodb://localhost:27017/expresspost'
}

Okay, now install the Mongoose library using the following command.

yarn add mongoose

# or

npm install mongoose --save

In my local MongoDB database, the username and password are empty, but you need to create one admin user and assign the database to that user in the production.

Now, import this db.js file into the server.js file.

// server.js

const express = require('express');
const mongoose = require('mongoose');

const app = express();
const PORT = process.env.PORT || 3000;

const config = require('./db');

mongoose.connect(config.DB, { useNewUrlParser: true }).then(
  () => {console.log('Database is connected') },
  err => { console.log('Can not connect to the database'+ err)}
);

app.listen(PORT, () => {
  console.log('Server is running on PORT:',PORT);
});

Here, we have connected our node express app to the MongoDB database.

Step 3: Install the body-parser module.

We need to install a body-parser module to handle the HTTP POST request in Express.js version 4 and above, and you need to install the middleware module called body-parser

The body-parser extracts the entire body portion of an incoming request stream and exposes it on the req.body.

yarn add body-parser

# or

npm install body-parser --save

The body-parser parses the HTTP request body. It is usually necessary to know more than just the URL you send to the server, particularly in a POST or PUT or PATCH HTTP request where the information you want is contained in the body.

Primarily it is a middleware for parsing the JSON data, plain text as you require.

After adding the body-parser, our server.js file looks like this.

// server.js

const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');

const app = express();
const PORT = process.env.PORT || 3000;

const config = require('./db');

mongoose.connect(config.DB, { useNewUrlParser: true }).then(
  () => {console.log('Database is connected') },
  err => { console.log('Can not connect to the database'+ err)}
);

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.listen(PORT, () => {
  console.log('Server is running on PORT:',PORT);
});

 Step 4: Create a Mongoose Model.

Inside the root, create one file called User.js and add the following schema to it.

// User.js

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const User = new Schema({
  name: {
    type: String
  },
  email: {
      type: String
  }
},{
    collection: 'users'
});

module.exports = mongoose.model('User', User);

So, here we have defined our schema for the users’ collection. It contains two fields.

  1. name
  2. email

Step 5: Create Express routes for the application.

Inside the root folder, create one file called UserRoute.js and add the following code.

// UserRouter.js

const express = require('express');
const UserRouter = express.Router();

const User = require('./User');

UserRouter.route('/create').post(function (req, res) {
  const user = new User(req.body);
  user.save()
    .then(user => {
      res.json('User added successfully');
    })
    .catch(err => {
      res.status(400).send("unable to save to database");
    });
});

module.exports = UserRouter;

We have used the POST request to store the data inside the MongoDB database.

We have already installed and configured the body-parser middleware to extract the data that can be used and save it into the database.

Now, import this file inside the server.js.

// server.js

const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');

const app = express();
const PORT = process.env.PORT || 3000;

const config = require('./db');
const UserRoute = require('./UserRoute');

mongoose.connect(config.DB, { useNewUrlParser: true }).then(
  () => {console.log('Database is connected') },
  err => { console.log('Can not connect to the database'+ err)}
);

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.use('/user', UserRoute);

app.listen(PORT, () => {
  console.log('Server is running on PORT:',PORT);
});

Step 6: Send a Post request From Postman

Okay, now we need to send a request to a Node server.

Make sure you have running the Node.js server. If not, then you can start it with the following command.

nodemon server

If you send an express post request to the server, it returns the following json. Remember, you need to add form data which is name and email. 

Here, you need to select the x-www-form-urlencoded to get the data into the req.body.

Express POST Body Example | body-parser tutorial with example

Now, check the MongoDB database.

express body-parser tutorial with example

So, here, we have successfully saved the data using the express post request example.

We can see the request by logging in to the console. Just put the console.log statement inside the UserRoute.js file.

// UserRoute.js

UserRouter.route('/create').post(function (req, res) {
  const user = new User(req.body);
  console.log(user);
  user.save()
    .then(user => {
      res.json('User added successfully');
    })
    .catch(err => {
      res.status(400).send("unable to save to database");
    });
});

Output

node express post example tutorial

That’s it for this tutorial. Thanks for taking it.

1 Comment
  1. Hashim Warren says

    thanks for this. How do you send a POST request from an HTML form?

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.