”;
We have set up the development, now it is time to start developing our first app using Express. Create a new file called index.js and type the following in it.
var express = require(''express''); var app = express(); app.get(''/'', function(req, res){ res.send("Hello world!"); }); app.listen(3000);
Save the file, go to your terminal and type the following.
nodemon index.js
This will start the server. To test this app, open your browser and go to http://localhost:3000 and a message will be displayed as in the following screenshot.
How the App Works?
The first line imports Express in our file, we have access to it through the variable Express. We use it to create an application and assign it to var app.
app.get(route, callback)
This function tells what to do when a get request at the given route is called. The callback function has 2 parameters, request(req) and response(res). The request object(req) represents the HTTP request and has properties for the request query string, parameters, body, HTTP headers, etc. Similarly, the response object represents the HTTP response that the Express app sends when it receives an HTTP request.
res.send()
This function takes an object as input and it sends this to the requesting client. Here we are sending the string “Hello World!”.
app.listen(port, [host], [backlog], [callback]])
This function binds and listens for connections on the specified host and port. Port is the only required parameter here.
S.No. | Argument & Description |
---|---|
1 |
port A port number on which the server should accept incoming requests. |
2 |
host Name of the domain. You need to set it when you deploy your apps to the cloud. |
3 |
backlog The maximum number of queued pending connections. The default is 511. |
4 |
callback An asynchronous function that is called when the server starts listening for requests. |
”;