AppDividend
Latest Code Tutorials

Express Post Request Example Tutorial

1,313

Get real time updates directly on you device, subscribe now.

Express Post Request Example Tutorial is today’s leading topic. When we use Node.js as a platform, then we almost use expressjs as our web framework. So when we are building applications using ExpressJS, we will need to get information from our users. In the HTTP sense, we have two main ways to collect the data from the user via browser and that is GET and POST. In this example, we use the POST method to obtain the information from the User. So when a user sends a request from the client, we receive the request and extract the data from the request and save the data into the database.

Earn a Tech Degree and get the skills like Frontend Development or Javascript Development that can help you to launch a career. Join the program

Express Post Request Example Tutorial

We start our demo by installing expressjs. 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 .

#1: Install Expressjs.

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 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

#2: Connect Express app to MongoDB database.

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

mongod

Now, inside the root of the project folder, create one file called db.js and add the following code in 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 in the production, you need to create one admin user and assign the database to that user.

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.

#3: Install body-parser module.

We need to install body-parser module because to handle the HTTP POST request in Express.js version 4 and above; you need to install middleware module called body-parser. The body-parser extract the entire body portion of an incoming request stream and exposes it on req.body.

yarn add body-parser

# or

npm install body-parser --save

The body-parser parses the HTTP request body. It usually is necessary when you need to know more than just the URL you send to the server, particular in the context of 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.

Related Posts
1 of 17

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);
});

 #4: Create a Mongoose Model.

Inside the root, create one file called User.js and add the following schema in 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

#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;

Here, we have used the POST request to store the data inside MongoDB database. We have already installed and configured the body-parser middleware, so we can extract the data that can be used and save 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);
});

#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 by the following command.

nodemon server

Now, if you send an express post request to the server, then 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 so that you can 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 express post request example.

We can see the request by logging in 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");
    });
});

 

node express post example tutorial

Finally, Express Post Request Example is over. Thanks for taking.

Leave A Reply

Your email address will not be published.

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