How To Create a Server Using ExpressJS

Posted By : Subham Das | 30-Mar-2021

nodejs Server

Loading...

Initially, we need to understand What is Express?

ExpressJS is a web application framework for Node.js. It is fast, flexible, and a minimal web application framework that provides various features, tools, and utilities to easily build the application. Express eases the server-side scripting. Express is a robust tool for creating web API and has a lot of innumerable methods and utilities which can build web APIs quickly. Express is a nodejs module , we cannot have express without nodejs.

Let's come to our code editor and create a file.

Install Express module using npm

npm install express --save

In our file we need to import express :

Const express = require('express');

Setting app variable

const app = express();

This statement will create a new express application for us and store it in an app variable.

Then, we need to assign a port number for our server configuration.

const PORT = process.env.PORT || 4400 ;

If we host our web application with some other service providers like AWS Beanstalk, Azure app service, Heroku, etc. So, our host will configure itself the PORT, and if you don't provide process.env.PORT then you can get 500 gateway errors. And if it is not present or you are running a local server then it will use our default PORT 4400 and this could be any number.

Setting a view Engine:

app.set('view engine', 'ejs' ) ;

put your ejs html file in your views folder.

Then we will add app.get() function for getting Get Requests:

app.get('/', (req,res)=>{

res.render('home')

})

app.get() needs a two parameters route and callback which will render our HTML.

Now only last thing is left, that we have to listen to our requests:

app.listen(PORT, ()=>{

console.log(`Listening on ${PORT}`);

})

Run it from your command prompt

node [filename] || node server


At Oodles ERP, we provide full-scale enterprise solutions with a focus on building custom Web applications. Our end-to-end Web application development services enable organizations to enhance their productivity and improve operational efficiency. For more information, contact us at [email protected].