Express.js -- Putting the "fun" in Fundamental
Express.js/Express is a minimal and a flexible web application framework for Node.js, which is designed for building web applications and APIs.
Below is a step by step demonstration of how to build a simple Express app -- quite possibly the simplest. So, let's get started now, shall we?
Installing Express
Assuming you have already installed Node.js on your computer, first we have to create a directory to contain the application. And then, enter the directory you created to make it your working directory.
$ mkdir myapp
$ cd myapp
Next, we have to create a package.json file for our application.
$ npm init
This command prompts us to enter details such as the name, version, description and the author of our application. But for now, we will hit RETURN and accept the default values for those fields, except for the entry point of your application.
entry point: (index.js) app.js
It gives the default value, index.js. You can choose to keep it by hitting RETURN, or else you can change it to something like app.js.
Next step is to install Express in our myapp directory and save it in the dependencies list.
$ npm install express --save
Now that we are done with installing Express, let's continue with the rest of our application.
My First Express Application
As you recall, we gave our entry point as app.js in one of the previous steps. Now, what we have to do is create a JavaScript file named app.js in our myapp directory and add the following code into that file.
var express = require('express')
var app = express()
app.get('/', function (req, res) {
res.send('My First Express Application!')
})
app.listen(3000, function () {
console.log('App listening on port 3000!')
})
Here, the app starts a server and listens on port 3000 for connections. The app responds with "My First Express Application!" for requests to the root URL(/), or route. For every other path it responds with a 404 FileNotFound error message.
To run our application we give following command.
$ node app.js
Last, but not least, load http://localhost:3000/ in a browser and observe the output.
Your output should look like this.

Nice blog. You have provided such a useful informartion in this blog. Thanks for sharing.
ReplyDeleteNode JS Online Training