To create a basic server in Node JS using Express we need these prerequisites
- Node JS
- Express JS
Steps to create a server
- Create an app.js file
- 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
- In first line, we are including express in our app.js file.
- In next line , we are mounting/calling express function and storing it into app variable.
- In third line, we are using get method to create index route and when called this index route we are displaying 'Hello world';
- 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
- Open terminal
- Go to that directory that contains app.js file
- 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