Create Express Server in Node.js

Create Express Server in Node.js

4 Easy Steps to Create Express Server

Express.js or simply Express is a light-weight web application framework to help organize your web application into an MVC architecture on the server side. We can use a variety of choices for our templating language (like EJS, Jade, and Dust.js). It is designed for building REST APIs. It has been called the de facto standard server framework for Node.js.

Steps to Create Express Server

Follow the below steps to create Express server

Create a empty directory

Open the command prompt and enter the command to create a directory

mkdir web-servers

Initialize NPM

On the root of the directory enter the following command to initialize the npm.

Note: In order the execute the above command, you should be installed Node.js on your system

npm init -y

npm init will initialize the npm with package.json file.

-y flag will provide the default values for the package.json file.

The generated package.json file looks like this

{
  "name": "web-servers",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

It contains the information about name of the application, version, description, author etc..

Install Express Server

In order to create Express server, we need to install Express npm library. On the root of the folder, enter the following command to install Express library.

npm install express

It will install the Express library and register the dependency inside the package.json file.

Create a Express Server

On the root of the folder, create a file app.js and add the following code

const express = require('express');

const app = express();

app.get('', (req, res) => {
    res.send('<h1>Hello Express!</h1>');
})

app.listen(3000, () => {
    console.log('Server is up and running');
})
  • At the top, we will load the express library using require() method

  • Next, we will create Express server using express() method which is the only method provided by Express library

  • We will return a HTML static content to the default route /

  • Last, we will call the listen() method to start the express server on the port 3000

Test the application

Open the web browser and navigate to the URL localhost:3000

image.png

That's it for this post. I hope you guys learnt creating the Express server in Node.js Thank you so much for reading. I will see you next time.