Express.js Web Application
Now that we installed express.js globally, we will build a web application using Express.js.
Create a folder name EXPRESS_WEBSERVER, navigate into the folder using command prompt and run the following command.
By default, the project contains package.json
file only.
Create a file named app.js and copy the following contents to it.
app.js
var express = require('express')
var app = express()
app.get('/', function (req, res) {
res.send('This is a basic Example for Express.js by TUTORIALKART')
})
var server = app.listen(8000)
We will be using Visual Studio Code for this Node.js project.
Open a terminal and run this application by running the command node app.js
.
No errors. The server is up and running.
Let us open a browser and hit the url http://localhost:8000/.
Let us see what we have done there in app.js
.
var express = require('express')
We imported express
package into app.js
using require
function.
var app = express()
We created an instance for an application by calling express()
function. This application function now acts as an independent. We can use this application instance to make it listen on port for requests, or some other functionalities which we will see in the next topics of this Express.js Tutorial.
app.get('/', function (req, res) {
res.send('This is a basic Example for Express.js by TUTORIALKART')
})
This is a route definition in Express.js. We will discuss in detail about routing in Express.js in our next topics. But remember that this is a route.
This particular route handles GET requests: app.get
.
This route is run for the path '/'
.
The function function(req, res){}
gets executed when a client sends a GET reques for the path ‘/’. The req
and res
hold the request and response objects respectively for this GET request.
res.send()
sends the argument to this function as response to the client.
var server = app.listen(8000)
We started the express application server to listen on port 8000.
You can also provide a function as an optional argument to the listen function, which gets executed after the server is up and running on the port specified.
Summary
In this Express.js Tutorial, we have learned how to create a web server application in Node.js using Express.js framework. Also, we got introduced to routing, but again, we will learn in detail about Express.js routing.