Creating a server in NodeJS using Express JS

Creating a server in NodeJS using Express JS

To create a basic server in Node JS using Express we need these prerequisites

  1. Node JS
  2. Express JS

Steps to create a server

  1. Create an app.js file
  2. Inside app.js file , write this code
let express = require('express');

let app = express();

app.get('/',(request,response)=>{
   response.send('Hello World');
});

app.listen(3000,()=>{
console.log('Server is running at port 3000')
});

Explanation of above code

  1. In first line, we are including express in our app.js file.
  2. In next line , we are mounting/calling express function and storing it into app variable.
  3. In third line, we are using get method to create index route and when called this index route we are displaying 'Hello world';
  4. Here we are telling app.js where to listen this server (on port 3000) and when server gets started we are displaying a message in the console that says Server is running at port 3000

To run the server

  1. Open terminal
  2. Go to that directory that contains app.js file
  3. Write this command -
node app.js

If everything goes right,you can see this message Server is running at port 3000 in your terminal.

Happy Coding