Creating a hello world application using Express.js

sujesh thekkepatt
2 min readNov 12, 2019

This is yet another tutorial on getting started with Expressjs. Express js is one of the popular frameworks for creating API-servers/web application in Nodejs. We can quickly prototype a new application using express. Many popular API services embed express under the hood eg: loopback. Most of them provide support for Express.

What makes Express popular among developers?

Of course the simplicity. You can quickly prototype and experiment with your application in a couple of minutes. You can easily create routes, deliver static assets, debug and support for templating languages are some of its features. The most important feature is the middleware. You can quickly add different middlewares to your routes thus enhancing route handling capabilities.

Middlewares

Middlewares are functions that have access to request, response objects, and the next function. Some middleware functions also have access to error (err) objects. Error objects are usually used in error handling middleware. You have full access to request/response objects. You can modify the object and pass it to the next available middleware using the “next” function. The “next” function is also used to propagate errors. You can pass next(“Some Error”) to indicate that there was some error. So let’s get our hands dirty and write some code.

Let’s start by installing express.js. If you haven’t downloaded nodejs yet install it from here. Open up your terminal and type the following,

“npm install express — save”

Now create an “index.js” file in your directory and code the following,

gist from Github

Here we required the express module and initialized a skeleton express object to the app constant. We also defined a PORT constant and assigned a value of 8080. Port, is where an application listening for incoming requests. You can have any value for that. Now we define a root handler for our application(ie ‘/’ path). We are defining a simple get route.

In Express you can create a route by specifying your HTTP verb and handler. Like app.http_Verb(path,handler).

Here our route handler function does nothing pretty much other than sending a “Hello world!!” as the response.

We will bind and listen to the port for incoming requests by using the “app.listen” method. This also takes an optional call back handler which executes after binding the port.

Now let’s run the app. To run simply type the following in your terminal from the working directory.

node index.js

Now direct your browser to here (Works only for localhost). You can see “Hello world!!” as the response.

We created a basic express application. It’s that simple to create an application using Expressjs. You can refer official express site for more detailed concepts.

--

--