Check out bidbear.io Amazon Advertising for Humans. Now publicly available 🚀

Express + Postman: Writing and Testing Routes

Intro

We have already covered the Express .get() request type pretty thoroughly (.get Basics, Express Route Parameters). Now we will get into the .post() request. This is where we will be receiving data from the user, for example information in a form. It is a request to add something to our server/database.

The full tutorial on HTML Inputs is located here. However as a quick refresher:

Form Attribute Refresher

We covered forms in this post: HTML 5 Basics – Forms

<form> represents a document section that contains interactive controls to submit information to a web server. Common attributes of <form> include:

action=”the url to send form data to”

method=”the type of http request, get or post” (this is a Boolean option)

<input> creates interactive controls. Then the <type> attribute determines the type of input. For example text, date, color, file, checkbox.

A full list of inputs are available here.

Exercise Setup

Let us first set up our application to receive some data. We will make a page that is a simple list, generated from an array. And then we will post new friends to the array/list. Start with a template called friends.ejs

<h1> A List of Friends </h1>

<% friends.forEach(function(friend){ %>
    <li><%= friend %></li>
<% }); %>

And in our application we create a route that serves our template when the /freinds URL is requested, and also defines an array of friends to start.

app.get("/friends", function(req, res){
    
    // array of friends
    var friends = [
        "Tony",
        "Jake",
        "Paul",
        "Jones",
        "Davis",
        "Terry"
        ];
        
    // render friends template
    res.render("friends.ejs", {friends: friends});
    
});

Note that we have placed res.render() after the array. Remember that Javascript is analyzed sequentially, and also that we can only give one response per route. Response is like the return function in vanilla JS. Once you hit return inside the function, the function is over and anything after that is null.

In this instance, if we place res.render before the array, we will get an error that the array has not been defined. The function will have exited before it reached the point that the array was defined.

Our .forEach loop in the template will loop over our array and give us the following:

list of friends

Creating the Post Route

app.post()

Create a simple post route in your application to a new URL /addfriend that simply responds with a message “Data Received”.

app.post("/addfriend", function(req, res){
    res.send("Data Received");
});

Test the route using a Postman post request on our new URL and we receive the applications response.

test route in postman

Adding a Text Input Form

Expand on this by creating a text input form that will return the user input instead of a pre-defined string. Add the form to the friends.ejs template.

<form action="/addfriend" method="POST">
    <input type="text" name="newfriend" placeholder="name">
    <button> Add Friend </button>
</form>

name = route key

The name that you give the input is the key that you will reference in your route.

Capturing Data From Form

req.body (body-parser)

Unlike the req.params object which can be captured automatically by Express, req.body requires an npm package to convert the body data into a Javascript object. There are several packages that will do this. In this instance we will be using body-parser.

$ npm install body-parser

and we add this package as a requirement in the setup portion of our application

// require body-parser module
var bodyParser = require("body-parser");
// tell express to use body-parser. more detail on this in the body-parser docs
app.use(bodyParser.urlencoded({extended:true}))

Now we add req.body to our route.

// "add friend" form endpoint
app.post("/addfriend", function(req, res){
    console.log(req.body)
    res.send("Data Received");
});

req.body is an object that will contain all of the data from the request body. Remember objects are similar to arrays. This is just a data dump of everything that is submitted to the /addfriend url with a post request. In this case it will be coming in the object format.

If you need a refresher on all the data that included with every request submission, that is covered here: Ncoughlin: Express.js Route Parameters

Testing the Form

With all of that done we can now test our form and see if we get the data back as an object in the console.

inputting a name into the add friend field

We input the name Jennifer

data received message

we get our response message

console log: newfriend: 'jennifer'

and we get our object logged in the console. Brilliant!

Refining the request

We got the object that we wanted. However, we got ALL the objects in the body, and we just want to get newfriends specifically. We can further refine our request from req.body to req.body.newfriend

// "add friend" form endpoint
app.post("/addfriend", function(req, res){
    console.log(req.body.newfriend);
    res.send("Data Received");
});

jennifer in console

and that will return the string that was input directly. Which is what we need to add to our names array.

Adding the Data to the Array

It’s worth noting that this exercise is a bit wonky, because typically we would be connected to a database and we would be pushing this data to that database. But we don’t have a database, we are just pushing to a hard-coded array in our app file. As soon as the server restarts, any friends that have been added will be erased. Understanding that oddity. Lets continue.

Now that we have figured out how to capture the string, lets put it in a variable, like so

// "add friend" form endpoint
app.post("/addfriend", function(req, res){
    console.log(req.body.newfriend);
    var newFriend = req.body.newfriend;
    res.send("Data Received");
});

The obvious solution would be to just .push(newFriend) to the friends array. However currently in our application the friends array is not available in the global scope. It is nested in a function:

// ***************************
// ROUTES
// ***************************

// homepage 
app.get("/", function(req, res){
    // render homepage template
    res.render("home.ejs");
});

// friends page. displays friends and add friend form
app.get("/friends", function(req, res){
    
    // array of friends
    var friends = [
        "Tony",
        "Jake",
        "Paul",
        "Jones",
        "Davis",
        "Terry"
        ];
        
    // render friends template
    res.render("friends.ejs", {friends: friends});
    
});

// "add friend" form endpoint
app.post("/addfriend", function(req, res){
    console.log(req.body.newfriend);
    var newFriend = req.body.newfriend;
    friends.push(newFriend);
    res.send("Data Received");
});

So to get access we need to move it into the global scope like so

// ***************************
// VARIABLES
// ***************************

 // array of friends
    var friends = [
        "Tony",
        "Jake",
        "Paul",
        "Jones",
        "Davis",
        "Terry"
        ];

// ***************************
// ROUTES
// ***************************

// homepage 
app.get("/", function(req, res){
    // render homepage template
    res.render("home.ejs");
});

// friends page. displays friends and add friend form
app.get("/friends", function(req, res){
        
    // render friends template
    res.render("friends.ejs", {friends: friends});
    
});

// "add friend" form endpoint
app.post("/addfriend", function(req, res){
    console.log(req.body.newfriend);
    var newFriend = req.body.newfriend;
    friends.push(newFriend);
    res.send("Data Received");
});

And if we go back and add Jennifer now

data received

We have a small problem which is that we are still being re-directed to the response of /addfriend. However if we refresh the page…

jennifer at bottom of list

Jennifer made it. But now we want to re-direct back to this page automatically.

res.redirect()

res.redirect() is a method that lets us re-direct to another page for our response. In this case we want to re-direct back to the /friends page so we can immediately see our new friends get added. So we just modify the response of our /addfriend post request

// "add friend" form endpoint
app.post("/addfriend", function(req, res){
    console.log(req.body.newfriend);
    var newFriend = req.body.newfriend;
    friends.push(newFriend);
    res.redirect("/friends");
});

and now we will be re-directed immediately back to the /friends page where we started, and we can see our additions to the array take place immediately.

GitHub Repo

Ncoughlin: Postman Routing Exercise

Amazon Ad Analytics For Humans

Advertising reports automatically saved and displayed beautifully for powerful insights.

bidbear.io
portfolios page sunburst chart