Express.js Routes

An Express.js Route defines how our Express application can respond to a client request to with a specific URI (or path) and a specific HTTP request method (GET, POST, etc.).

To understand the need of an Express.js Route, let us dive into an example.

Create a basic Express application as shown beow.

app.js

All we have done is, instantiate an express application, started it at port 8000. Now, open a browser and hit the url http://localhost:8000/.

Express.js Cannot get /

The reponse is that it cannot GET the resource ‘/’.

Even there is no error in the console. The app is running fine.

Express.js app running

Why is that? Because, in our Express application, we started the server, but did not define what has to happen when a request hits the server.

This is where Express.js Routes come into picture. Following is a simple express route.

What does this route define? This route defines that, execute the statements inside the function, when you receive a GET request with request url as /.

In the following screenshot is a route, where the function is executed for a GET request with request url /hello/.

Express.js Route

Let us define some routes in our app.js and start the server.

app.js

Start the express application..

Express.js app running

Now hit the urls in the browser. By default, browser sends a GET request.

GET request with URL path http://localhost:8000/

Node.js Express Route 1

GET request with URL path http://localhost:8000/hello/

Node.js Express Route 2

GET request with URL path http://localhost:8000/bye/

Node.js Express Route 3

Express route with multiple functions

You can provide one or more functions in the route. Each function is called a middleware. [Reference: Express.js Middleware]

app.js

And in the browser, output is

Express.js Route with multiple middleware

You can also define these functions separately for modularity as shown below.

Summary

In this Express.js Tutorial, we have learned what an Express.js Route is, how to define Express.js Route, and how to use these Routes to serve different kinds of HTTP methods against different URL paths.