Before beginning with ExpressJS make sure you have nodejs installed on your machine.
What is ExpressJS?
ExpressJS is a NodeJS framework for creating server-side applications. ExpressJS provides many shorthand methods for writing the functionality provided by NodeJS.
Installing ExpressJS
Step 1
Go to your application directory.
Step 2
Initialize your node project (create package.json) using the following command. When asked for entry point, enter index.js or whatever you want it to be.
Step 3
Now to install use following command. –save will update the dependencies in package.json file.
- npm install express --save
Creating our first application using ExpressJS.
Inside our index.js file add the following lines of code.
- var express = require('express');
- var app = express();
- app.get('/', function (req, res) {
- res.send('This is our first ExpressJS application.');
- });
- app.listen(3000, function () {
- console.log('Example app listening on port 3000!');
- });
In the first two lines we are importing Express module and using its reference we are assigning the returned result to ‘app’ variable. The express() function when called actually returns the object which contains all the methods which we need to use to build our ExpressJS application. Once we have the reference saved in our app variable, we can use it to call various methods like get, put, listen.
The get() method accepts two params, first one is a particular route and second one is a callback method which has two parameters, request and response. In our case the route which we have used is ‘/’ which means the home of our application and inside the callback method we are returning a string using response. We can either send normal text string or html string via server response.
The listen() method is used to set the port on which our server will listen/wait for requests to come and then handle them accordingly. We have set the port to 3000 so the home page for our application will be http://localhost:3000.
Now we can start the application by going to command prompt then inside our application directory and running the application using,
This command will start the server and it will be active on port 3000. Using our browser we can go to http://localhost:3000 and see the response from the server. Any other path except http://localhost:3000 will result in 404 Page Not Found error.
Using the get() method we can make different routes like get(‘/about’), which can do various operations like returning a json file, making database call and return the result.
Express provides different routing handler methods which we will look into in more detail in another section.