To send a post request in the Node.js express framework, use the “express.Router().route().post()” method. The data sent through the POST request is stored in the request object.
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 .
Here is the step-by-step guide to creating a POST request and sending it to the server with data as a payload.
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.
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
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'
}
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 must create one admin user and assign the database to that user in production.
Now, import this db.js file into the server.js file.
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. Knowing more than just the URL you send to the server is usually necessary, 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.
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.
Create one file called User.js inside the root and add the following schema.
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.
- name
Step 5: Create Express routes for the application.
Create one file called UserRoute.js inside the root folder 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
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.
Now, check the MongoDB database.
So, 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
That’s it for this tutorial. Thanks for taking it.
Hashim Warren
thanks for this. How do you send a POST request from an HTML form?