Express js First App

We hope, you have successfully installed express. Now let's create a simple first express.js application.

var express = require("Express");
var app = express();

app.get("/", function(request, response){
	response.send("Hello World!");
});

app.listen(3000, function(){ 
	console.log('Server is running at http://localhost:3000');
});

Explanation of the above code


var express = require("Express");

It includes express and puts in a variable.


var app = express();

It creates a new express application inside app variable.


app.get("/", function(request, response){
	response.send("Hello World!");
});

It is a request handler that defines the route and sends 'Hello World'. A request handler is a function that will be executed every time the server receives a particular request, usually defined by HTTP method. It accepts two parameters request and response.


app.listen(3000, function(){ 
	console.log('Server is running at http://localhost:3000');
});

It starts the server on 3000 port.


Run the application

In your working directory, create a file name 'firstapp.js' and save the above code. Now, open command prompt and run the app from the project folder using the following command.

$node firstapp.js
Express.js First App

Now open your web browser at 'http://localhost:3000'.


How Express.js works

Express.js has a main file, that is the main entry file. This file may contain configuration settings, template engine, routes, define middleware such as static file handler, error handling, cookies and other parsers.





Read more articles


General Knowledge



Learn Popular Language