Getting Started with ExpressJS

Express.js is a NodeJS web application framework. You can use ExpressJS to build Single Page, Multi Page or Hybrid applications.

Express can be installed via NPM (Node Package Manager) type below command in the command line

C:\Users\User>npm install express

We are going to simple Application using ExpressJS.

const express=require('express');
const app=express();
app.get('/', (req,res) => {
    res.send( 'Hello World' );
});
app.listen(3000, () =>console.log ('Listening on port 3000.....'));

save it as index.js , Lets understand one by one.

const express=require(‘express’)

Loan express module and save it to the express constant

const app=express();

express() returns object type Express

so this app object has bunch of useful methods such as

app.get()

app.post()

app.put()

app.delete()

In this code I am gonna demonstrate get() method only

app.get(‘/’,function(req , res){
res.send(‘Hello World!’);
});

app.get method takes two arguments

First one is Path or the URL here we use ‘/’ to indicate ROOT path

Second argument is callback function, this function is called when we get HTTP get request

function This res object has many properties, one is res.send(“Hello World”) Here we are going to send “Hello World” from server when we get HTTP get request.

app.listen(3000, () =>console.log (‘Listening on port 3000…..’))

Finally we need to listen on a given port, app;listen() method takes to parameters

First one is the port number and second one is additional method, I have used it to console.log.

Open Command line and tyoe

C:\Users\User> Node index.js

Type localhost:3000 on your browser tab

Let’s meet on another Post!!!!

Leave a comment

Create a website or blog at WordPress.com

Up ↑

Design a site like this with WordPress.com
Get started