April 26, 2024

ExpressJS Hello World Example

In this article we'll see how to create a Hello world application using ExpressJS. It is essentially going to be a web application, ExpressJS provides a robust set of features that makes it easy to create a web application using NodeJS.

Pre-requisite for creating Hello World example is to have NodeJS and ExpressJS installed in your system.

Need to install NodeJS, check this post- Installing Node.js and NPM on Windows

Hello World example using ExpressJS and Node

You can create a file named app.js and write the code as given below.

const express = require('express');

const app = express();
const port = 3000;

app.get('/', (req, res) => {
    res.send("<h3>Hello World from ExpressJS</h3>")

app.listen(port, () => {
    console.log(`Example app listening on port ${port}`)

Let's try to understand what has been done in the above code.

  1. First thing you need to do is to import ‘express’ package.
  2. From that we assign express() function to a constant app, that encapsulates a lot of express logic into the app constant.
  3. The app object has methods for routing HTTP requests. We'll use app.get(path, callback) method that routes HTTP GET requests to the specified path with the specified callback functions.
  4. Specified path in our code is root path ('/'), callback function receives two arguments request and response. The request object (req) represents the HTTP request and the response object (res) represents the HTTP response.
  5. Using res.send(body) function a HTTP response is sent back from the server.
  6. app.listen([port[, host[, backlog]]][, callback]) method binds and listens for connections on the specified host and port. In our example port is 3000 so that’s the port number to which server is bound to accept incoming requests. Host in this case is localhost so no need to specify it explicitly. Backlog denotes the maximum number of queued pending connections. Callback function is the function that is called once the server starts. In our example callback function displays a message on the console.

You can run the app with the following command:

$ node app.js

Server running at http://localhost:3000/

If you access URL http://localhost:3000/ you should see the response sent by the server.

That's all for the topic ExpressJS Hello World Example. If something is missing or you have something to share about the topic please write a comment.

You may also like

No comments:

Post a Comment