How To Setup Express Routes

How To Setup Express Routes

JavaScript is the language of the web and you are likely familiar with it running in all of your favorite web browsers. JavaScript also runs on the server via Node and in this tutorial, we’ll take a look at setting up routes in the popular Express framework. To start using Express, first, make sure Node is installed on your machine. You can check with the command node -v. If that checks out, go ahead and run npm install express to get Express installed. We are now ready to set up a server and start routing in Express!


Starting An Express Server

In a directory on your machine go ahead and create an app.js file. Inside of that file, we can start with this code here.

app.js

const express = require('express');
const app = express();

The first line imports the Express library into our program. The require() function does the heavy lifting for us here. Then on the next line we make a call to Express via express() and assign the result to the app constant. This is an instance of the Express application. With this, a JavaScript web server is now within reach.

A web server is used to listen for requests and then perform whatever action is needed to satisfy the request. Typically the webserver will also then return a response. To enable the server to start responding, we have to provide a port number argument to a method called app.listen() that tells the server where to listen for new requests. Once this is established the server will then listen on the specified port and respond to any requests that come into it.

app.js

// Import the express library
const express = require('express');

// Instantiate Express
const app = express();

// Configure the port to listen on
const PORT = process.env.PORT || 4001;

// Call the listen() method on the server object
app.listen(PORT, () => {
    console.log(`Server is listening on port ${PORT}`);
});

To run the application use the command node app.js in the terminal.
Server is listening on port 4001

The finished code above is a basic example of how to get a server running using Express. You can clearly see each step of the process.

  • Import the Express library
  • Instantiate Express
  • Configure the port to listen on
  • Call the app.listen() method

Create An Express Route

As soon as an Express server is listening, it can respond to requests made to it. In order for the server to understand what to do with a request, we need to set up routes. Routes define the control flow for requests based on the request’s path and the HTTP verb used such as GET or POST. Let’s add the following code to our app.js file.

app.js

app.get('/hello', (req, res, next) => {
    res.send('Hello Express!');
}); 

So what is happening here? The .get() method is called on the app Express instance. The first argument to the function is the path. In this case, that is ‘/hello’. This means that if you visit http://localhost:4001/hello in a web browser while the server is running, then the callback which is the second argument to get() will trigger. In this case, the callback is simply sending a response back to the browser with ‘Hello Express!’ as a response. Testing this in a web browser shows it working in action.

Create An Express Route

The HTTP verb is always included in the request and can be GET, POST, PUT, PATCH, or DELETE. These verbs are used to specify expected functionality. GET requests are used for retrieving resources from a server which is what this example code here does.

Express uses app.get() to register routes to match GET requests. As you can imagine app.post() would be for a POST request. Express routes typically take two arguments, a path (usually a string), and a callback function to handle the request and send a response.


Sending A Response

HTTP follows a one request-one response cycle. Each client expects exactly one response per request, and each server should only send a single response back to the client per request. Express servers send responses using the .send() method on the response object. .send() will take any input and include it in the response body.


Matching Route Paths

Express will try to match requests by route, in other words if we send a request to <server address>:<port number>/hello, the Express server will search through any registered routes in order and try to match /hello.

Routes are searched in the order that they are registered in your code when using Express as a server. The first one that is matched will be used, and its callback will be called. If there are no matching routes registered, or the Express server has not sent a response at the end of all matched routes, it will send back a 404 Not Found response, meaning that no routes were matched or no response was ultimately sent by the registered routes.


Express Route Parameters

Like any good web framework, you want to be able to capture parameters in the URL for more meaningful route patterns. Express servers provide this functionality with named route parameters. Parameters are route path segments that begin with : in their Express route definitions. They act as wildcards, matching any text at that path segment. For example /hello/:id will match both /hello/1 and /hello/3.

Express parses any parameters, extracts their actual values, and attaches them as an object to the request object: req.params. This object’s keys are any parameter names in the route, and each key’s value is the actual value of that field per request.

Suppose we have this new code in our application and we want to say hi to a different person based on the router parameter provided.

const names = {1: 'John', 2: 'Jane', 3: 'Joe'};

The goal is that when we provide a 1 in the URL as a route parameter, we’d like to say hi to John. If a 2 is provided, we’ll say hi to Jane, and so on. The code below should provide what we are looking for.

app.get('/hello/:id', (req, res, next) => {
    res.send(`Hello ${names[req.params.id]}`);
});

express route parameter 1
express route parameter 2
express route parameter 3

As we test the code out above in a web browser, we can see that we are now getting the result we expect.


Response Status Codes

An HTTP status code is a response sent by a server to a browser’s request. Browsers send a request to the site’s server when visiting a website, and the server then responds to the browser’s request with a three-digit code which is the HTTP status code.

Status codes communicate whether things between the two are working correctly, somewhat working, or whether something is wrong. Understanding status codes and how to use them makes it easier to diagnose site errors quickly to minimize downtime on your site. You can even use some of these status codes to help search engines and people access your site. For example, a 301 redirect will tell bots and people that a page has moved somewhere else permanently. Your favorite status code will likely be 200 OK, since that means everything is working well.

Express allows us to set the status code on responses before they are sent. Response codes provide information to clients about how their requests were handled. The res object has a .status() method to allow us to set the status code, and other methods like .send() can be chained from it. We can modify our little hello application to only send back a valid Hello message if the ID is found in the names constant. If the ID is nonexistent, we can instead send a response with a status code of 404 which means not found.

const names = {1: 'John', 2: 'Jane', 3: 'Joe'};

app.get('/hello/:id', (req, res, next) => {
    if (names[req.params.id]) {
        res.status.send(`Hello ${names[req.params.id]}`);
    } else {
        res.status(404).send('ID Not found');
    }
    res.send(`Hello ${names[req.params.id]}`);
});

HTTP PUT POST DELETE

The HTTP protocol has several different method verbs with different use cases. The GET request is the most common of all the HTTP verbs. Each time your browser loads an image, it is making a GET request for that file!

The other important HTTP methods are PUT, POST, and DELETE. Express provides methods for each one in the form of app.put(), app.post(), and app.delete().

When you need to update an existing resource you can use a PUT request. Let’s try implementing a PUT request below.

const names = {1: 'John', 2: 'Jane', 3: 'Joe'};

app.put('/hello/:id', (req, res, next) => {
    // PUT /hello/1?name=Jimmy
    names[req.params.id] = req.query.name;
    console.log(names);
    res.send(names[req.params.id]);
});

Note the existing names const with the names of John, Jane, and Joe. With the code above we should be able to send PUT requests in a specific format to update that existing data. For example, we will be testing the following PUT requests.

PUT http://localhost:4001/hello/1/?name=Sam

PUT http://localhost:4001/hello/2/?name=Susan

PUT http://localhost:4001/hello/3/?name=Shelley

Entering those URLs into a web browser will not work because a web browser is only going to send GET requests. We need to make PUT requests. So how do we do that? A really super-easy way to do this is by using the REST Client for Visual Studio Code. With this tool, you simply add a file to your project with a .http extension such as test.http and then add the request you would like to make. Once you have a valid REST request, the file will display a clickable Send Request link. When you click that link, the provided request is made and the HTTP request and response are displayed in beautiful formatting.

First, make sure Express is running:

launch express server

Then, in your test.http file, go ahead and the request you would like to make, then click Send Request:

send put request vs code

Now observe the magic. In the side pane you will see the request and response:

rest client request response

In the console, we can see that the first id has been updated from John to Sam via our PUT request.

{ '1': 'Sam', '2': 'Jane', '3': 'Joe' }

Let’s go ahead and update id 2 now.

rest client put reqest
rest response

{ '1': 'Sam', '2': 'Susan', '3': 'Joe' }

Lastly, we update id 3.

test put request to express
put request response

{ '1': 'Sam', '2': 'Susan', '3': 'Shelley' }

Using POST In Express

POST is the HTTP method verb used for creating new resources. Because POST routes create new data, their paths do not end with a route parameter, but instead, end with the type of resource to be created.

For example, to create a new color, a client would make a POST request to /colors. The client does not know the id of the color until it is created and sent back by the server, therefore POST /colors/:id doesn’t make sense because a client couldn’t know the unique id of a monster before it exists.

Express uses .post() as its method for POST requests. POST requests can use many ways of sending data to create new resources, including query strings.

The HTTP status code for a newly-created resource is 201 Created.

Let’s create some colors on the server using POST and a JSON payload. First, we need to tell Express that we want to use JSON data.

// Use json
app.use(express.json())

Now let’s use the following code in app.js

colors = [];

app.post('/colors', (req, res, next) => {
    colors.push(req.body.color);
    res.status(201).send(req.body.color);
    console.log(colors);
});

Now we simply make a few requests using the Rest Client tool.

Request

POST http://localhost:4001/colors
content-type: application/json

{
    "color": "Red"
}

Response

HTTP/1.1 201 Created
X-Powered-By: Express
Content-Type: text/html; charset=utf-8
Content-Length: 3
ETag: W/"3-zJ2zp5VXHH5x9FZwodp/9JtfFVc"
Date: Thu, 24 Mar 2022 14:13:01 GMT
Connection: keep-alive
Keep-Alive: timeout=5

Red

Console

[ 'Red' ]

Request

POST http://localhost:4001/colors
content-type: application/json

{
    "color": "Green"
}

Response

HTTP/1.1 201 Created
X-Powered-By: Express
Content-Type: text/html; charset=utf-8
Content-Length: 5
ETag: W/"5-kzvyGv3VWg0ig4Rf7Q57vdH120k"
Date: Thu, 24 Mar 2022 14:16:04 GMT
Connection: keep-alive
Keep-Alive: timeout=5

Green

Console

[ 'Red', 'Green' ]

Request

POST http://localhost:4001/colors
content-type: application/json

{
    "color": "Blue"
}

Response

HTTP/1.1 201 Created
X-Powered-By: Express
Content-Type: text/html; charset=utf-8
Content-Length: 4
ETag: W/"4-fUS8RJwqJjdIAKUD8Q89iUlQX0A"
Date: Thu, 24 Mar 2022 14:17:18 GMT
Connection: keep-alive
Keep-Alive: timeout=5

Blue

Console

[ 'Red', 'Green', 'Blue' ]

Delete

DELETE is the HTTP method used to delete resources. Because DELETE routes delete currently existing data, their paths should usually end with a route parameter to indicate which resource to delete.

Express uses .delete() as its method for DELETE requests.

Servers often send a 204 No Content status code if deletion occurs without error.

Let’s delete some colors from the server now.

colors = ['Red', 'Green', 'Blue'];

app.delete('/colors/:color', (req, res, next) => {
    let index = colors.indexOf(req.params.color);
    if (index > -1) {
        colors.splice(index, 1);
        res.status(204).send(`Deleted ${req.params.color}`);
    } else {
        res.status(404).send('Color Not found');
    }
    console.log(colors);
});

We can delete all three colors from the array like so.

DELETE http://localhost:4001/colors/Red HTTP/1.1
DELETE http://localhost:4001/colors/Green HTTP/1.1
DELETE http://localhost:4001/colors/Blue HTTP/1.1

The responses would look something like this meaning the delete operation succeeded.

HTTP/1.1 204 No Content
X-Powered-By: Express
ETag: W/"b-GTWhh9kyBtzeZKZXw6bPx3sal58"
Date: Thu, 24 Mar 2022 14:38:41 GMT
Connection: keep-alive
Keep-Alive: timeout=5

How To Setup Express Routes Summary

Congratulations, you have learned how to use GET, POST, PUT, and DELETE routes in the popular JavaScript Express library. With this knowledge, you now have all the tools you need to create a basic CRUD API using Express.