a blog for those who code

Friday, 8 January 2016

Creating your first Application in Express

In this post we will discussing about Coding your first application in Express. As you know Express is a minimal and flexible Node.js web application framework that provides a robust set of features to develop web and mobile applications. Before going any further I assume that you have completed Installation and Setup of Express, if not refer to Getting Started with Express - Installation and Setup.

To get started with the basic project in Express you need to have a variable of "Express" libraries and a variable of application on top of your app.js as shown below. 

var express = require('express');
var app = express(); //Initiates Express

Next we need to set up the some of the app environments as shown in the below code.The first app setting defines the port where your application will communicate, the second app settings tells your app where to find its views and the third app settings defines the engine which will render those views.

app.set('port', process.env.port || 5000); 
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

The next step is to creating a basic command to display some text on the web browser as shown below.

app.get('/', function(req, res) {
  res.send('Hello World Express');
}); 

Then we need a server to listen to requests pending for your application as shown below.

var server = app.listen(5000, function () {
  console.log('Listening on port ' + server.address().port)
});

Once done you will run the application by node app.js. If everything is right you can see that the server is listening on port 5000 and when you open http://localhost:5000 in the browser you can see the text you have written earlier.




Full Code:

var express = require('express');
var app = express();

var path = require('path');
var port = 5000;

app.set('port', port); 
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.get('/', function(req, res) {
  res.send('Hello World Express');
});

var server = app.listen(port, function () {
  console.log('Listening on port ' + server.address().port)
});

Please Like and Share the CodingDefined.com Blog, if you find it interesting and helpful.

No comments:

Post a Comment

Contact Us

Name

Email *

Message *

Sponsers

Best Hosting Plans

CC License