- ExpressJS - Resources
- ExpressJS - Best Practices
- ExpressJS - Debugging
- ExpressJS - Error handling
- ExpressJS - Scaffolding
- ExpressJS - RESTful APIs
- ExpressJS - Authentication
- ExpressJS - Sessions
- ExpressJS - Cookies
- ExpressJS - Database
- ExpressJS - Form Data
- ExpressJS - Static Files
- ExpressJS - Templating
- ExpressJS - Middleware
- ExpressJS - URL Building
- ExpressJS - HTTP Methods
- ExpressJS - Routing
- ExpressJS - Hello World
- ExpressJS - Environment
- ExpressJS - Overview
- ExpressJS - Home
ExpressJS Useful Resources
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
ExpressJS - Hello World
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.psten(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 pne imports Express in our file, we have access to it through the variable Express. We use it to create an apppcation 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 cpent. Here we are sending the string "Hello World!".
app.psten(port, [host], [backlog], [callback]])
This function binds and pstens 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 pstening for requests. |