DEV Community

Cover image for Getting Started With Express JS: A Beginner's Guide
Martins Ngene
Martins Ngene

Posted on

Getting Started With Express JS: A Beginner's Guide

There are so many JavaScript libraries and frameworks that are used for building APIs and servers but Express JS remains one of the best choices, especially for small or medium-scale projects.

Currently, express has a weekly download of over 11 million as shown in the NPM registry which shows that it's neither dying nor going away anytime soon.

Introduction

That said, we'll look at how to get an express server up and running in the least possible time. we will follow a simple project-based approach for which I have set up a repository which you can find here. I have included all of the code for the mini-project which you can find in this article.

We'll build a simple survey form with HTML and style our form with the CSS which we will serve as a static asset.

Mini Project: Survey Form

Project Setup

To create a new project, open your terminal and create a folder. The name of the folder should be the name you want to give the project. Then cd into the folder and initialize a new npm project (Make sure you have Node js installed). The steps are below:

// Step 1
mkdir myExpressServer

// Step 2
cd myExpressServer

// Step 3
npm init -y
Enter fullscreen mode Exit fullscreen mode

Installing Dependencies

We will need a couple of packages for the project so use the command below to install them:

npm install express nodemon cors dotenv body-parser

Dependencies are libraries that give you some utilities and out-of-the-box tools so you don't have to code everything from scratch.

Open the project in your code editor of choice and you will find a file named package.json it should look like this:

Package.json File

Now to structure our project we have to create some files and folders. Use the command below to create them in your terminal:

// Step 1
mkdir public 

// Step 2
touch .env .gitignore index.js public/index.html public/style.css
Enter fullscreen mode Exit fullscreen mode

Open the .gitignore file and add the following names:

node_modules
.env
Enter fullscreen mode Exit fullscreen mode

This prevents the files from being tracked by Git. The .env file is used to add secrets like passwords and API keys to our project; we don't want that on GitHub for everyone to see. While the 'node_modules' folder will take too much space if tracked by git. It may cause a slowdown when pushing to GitHub and it can be added with just a command when the repository is cloned using npm install

Project Set Up

Now open the index.js file and add this code:

require("dotenv").config();
const cors = require("cors");
const express = require("express");
const app = express();
const PORT = 3001;
const bodyParser = require("body-parser");

Enter fullscreen mode Exit fullscreen mode

The first line configures our app to use the .env file so we can access stored secrets. The second line imports the 'cors' library we installed earlier on. This library enables other applications (like a frontend app) to call the routes that we're about to create. The third line imports our express app and the fourth line instantiates it assigning it to a variable named 'app'. As we are about to see PORT is simply a variable that saves the port number where our app will listen. The last line imports the body-parser package which you'll soon see its use.

For us to use Nodemon (which helps us watch for changes in our app and reloads the app automatically), add this code to the scripts properties in your package.json file:
"start": "nodemon index.js 3001"
The result should be this:

Add start scripts to package.json file

Then call the listening method on your app and pass the PORT variable as a parameter:

app.listen(PORT, () => {
  console.log("Server is running on PORT " + PORT);
});
Enter fullscreen mode Exit fullscreen mode

The console.log is just for us to be sure that the server runs as expected.

Now on our terminal, we can start our project with:

npm run start

Our app will start on the port specified in the package.json file (which is port 3001. You can change this if you prefer another port)

Add this route to check if your setup is working and visit http://localhost:3001/ on a browser:

app.get("/", (req, res)=>{
res.send("Hello World")
})
Enter fullscreen mode Exit fullscreen mode

If you see "Hello World", then you did it correctly. Congratulations! 🥳 You just built an express server.

Delete the code below before you start building your app:

app.get("/", (req, res)=>{
res.send("Hello World")
})
Enter fullscreen mode Exit fullscreen mode

Building the App

So building our app, we will first set our static assets, and then we'll learn how to serve them. Open your index.html file in the public folder and add this code:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" href="/public/style.css" />
    <title>Codeland</title>
  </head>
  <body>
    <div class="container">
      <h1>Welcome to Codeland Survey</h1>
      <form action="/survey" method="post">
        <!-- Name -->
        <label>Name:</label>
        <input
          type="text"
          name="name"
          placeholder="Enter your name"
          required /><br />

        <!-- Email -->
        <label>Email:</label>
        <input
          type="text"
          name="email"
          placeholder="Enter your email"
          required /><br />

        <!-- Suggestions -->
        <label>How can we improve our services?</label><br />
        <textarea
          placeholder="Enter your suggestions here"
          name="feedback"
          id=""
          cols="30"
          rows="8"
          required></textarea
        ><br />

        <!-- Submit -->
        <input type="submit" value="Submit" />
      </form>
    </div>
  </body>
</html>

Enter fullscreen mode Exit fullscreen mode

Then open your style.css file from the same folder and add this code:


* {
  margin: 0;
  padding: 0;
  border: 0;
}

body {
  box-sizing: border-box;
  background-color: #a9d6e5;
}

.container {
  background: transparent;
  width: 80%;
  margin: 0 auto;
  display: flex;
  flex-direction: column;
  justify-items: center;
  align-items: center;
  padding: 50px 0px;
}

form {
  background-color: #61a5c2;
  width: 50%;
  padding: 20px;
  border-radius: 5px;
}

input,
textarea {
  width: 100%;
  margin-top: 5px;
  margin-bottom: 15px;
  font-size: 16px;
  font-weight: 600;
  padding: 10px 3px;
  outline: none;
}

h1 {
  margin-bottom: 10px;
  font-size: 40px;
}

label {
  font-size: 18px;
  font-weight: 700;
}

@media (max-width: 600px) {
  form {
    width: 80%;
  }
}

Enter fullscreen mode Exit fullscreen mode

Now we have our assets ready and can start building up the routes while learning some introductory concepts in Express JS.

Create a .env file in the root directory of your project and add this code:

// To access my credentials from .env file
const originUrl = process.env.ORIGIN_URL;

The next step is to configure our cors.

// To allow only a particular origin to access your server, create an object like the one below
// Then add it to the route you want to allow the origin to access
// or pass as an argument to the cors() if you want that origin to have access to all the routes on your server
let corsOptions = {
  origin: originUrl,
  optionsSuccessStatus: 200, // some legacy browsers (IE11, various SmartTVs) choke on 204
};

// To enable cross-origin resource sharing
app.use(cors());

// Body Parser is required to parse payloads coming from the front end.
// Without this, you'll get an error "TypeError: Cannot read properties of undefined (reading 'name')"
// Because the payload won't be parsed.
app.use(bodyParser.urlencoded({ extended: false }));
Enter fullscreen mode Exit fullscreen mode

What Is CORS And Why Is It Important?

CORS stands for Cross-Origin Resource Sharing. This is a mechanism that web applications use to communicate and share resources. For example, for a frontend application to communicate with our server via network requests, we need to tell our server to receive messages from the frontend app.

This helps guard our server against malicious attacks of hackers sending attacks from another origin or web application. If the origin URL of the hackers' web application is not registered on our server, our server will refuse to communicate with it thus mitigating the attack. To learn more about cors you can see the Mozilla Developers Network - MDN

Serving Static Assets

For us to work with our form, we need to see it in our browser. For this to happen, we have to expose the assets in our application so that they can be accessed from the port. Add the code below after the previous codes:

// Serve static assets from the public folder
app.use("/public", express.static(__dirname + "/public"));

The above line of code exposes the assets of our file but we still need to serve our HTML form on a particular route so we can see it.

// Serve a HTML file
const serveHTML = __dirname + "/public/index.html";

app.get("/", (req, res) => {
  res.sendFile(serveHTML);
});
Enter fullscreen mode Exit fullscreen mode

The above code exposes our form on the home route. Visit http://localhost:3001/ on a browser to view it.

You will find that the form has two inputs and one textbox. The next question is how do we get the data from the form on our server when a user fills it?

We will create an endpoint for that. First, notice the opening tag of the form element in your index.html file:

<form action="/survey" method="post">

You can see the action attribute already has an endpoint /survey. Let's create that endpoint. Add the code below after the previous ones:

// This endpoint returns a JSON object containing the details entered in the survey form
app.post("/survey", (req, res) => {
  const details = {
    name: req.body.name,
    email: req.body.email,
    feedback: req.body.feedback,
  };
  res.json(details);
});

Enter fullscreen mode Exit fullscreen mode

No need to freak out. Let me explain 🤓 On the app variable, we call a post method which takes in two parameters. The first is the endpoint, the second is a function to perform the tasks and communication associated with that endpoint.

You can see that we've named the endpoint to which we can send the form's data. Let's see what the function does. In simple terms, the req argument the function accepts stands for request. It's an object that any application allowed by the server uses to talk to a route on the server while the res argument stands for response and it's an object that the server uses to respond to the requests of the application.

That said, we can see that the req object contains another object as its property named body which contains the data of our form. We then save it into an object details and convert that object to JSON format then the server sends it as a response: res.json(details);

Now fill out the form and submit it. You will see that the data is returned as a JSON object.

Some More Details About The req object

Let's see some other information contained in the req object aside from the body. Add the code below after the previous codes:

// This endpoint shows some information about the machine of the user making a request to your server
app.get("/info", (req, res) => {
  const response = {
    ip: req.ip,
    path: req.path,
    method: req.method,
    message: "These are some info you can get from the request object",
  };
  res.json(response);
});
Enter fullscreen mode Exit fullscreen mode

Now visit the endpoint: http://localhost:3001/info and you'll get a response of an object with the ip and path of the route you visited. And a message property.

Sending Params To The Server Via Endpoints

Lastly, we will consider how to send parameters from the front end of our application to a route on our server to be used to perform a taste. Paste the code below after the previous codes:

// This endpoint shows how to get the params sent from the client side on the server
// To test the endpoint, visit the route attaching your localhost port.
// Then add a number of day of the week and it gets returned as a JSON object
// E.g localhost:3001/weekdays/1
app.get("/weekdays/:day", (req, res) => {
  const weekDays = [
    "Sunday",
    "Monday",
    "Tuesday",
    "Wednesday",
    "Thursday",
    "Friday",
    "Saturday",
  ];
  let day = req.params.day;
  res.json({
    dayOfWeek:
      day > 7
        ? "No such day of the week. There are only 7 days in the week"
        : weekDays[day - 1],
  });
});
Enter fullscreen mode Exit fullscreen mode

In the code above, notice how this endpoint is written:
/weekdays/:day. :day is the variable that is sent to the server as a parameter. : must be included to show it's a parameter the day can be given any name as you see fit.

We can access this parameter on the server from the req object. We find the params object and we get the day variable from it. Now visit this URL to test the endpoint: http://localhost:3001/weekdays/1. Change the number from 1 to 7 to get the names of different days of the week. A number outside this range will give you a message: No such day of the week. There are only 7 days in the week as a safeguard for higher figures.

Conclusion

Get the complete code on Github and don't forget to drop a star to support me 🤓

And there you go. A guide to get you started with Express JS. Of course, there are more things to learn about the framework but the things covered here will give you a great head start to using Express Js for building APIs.

I am Martins Ngene, A Software Developer and Technical Writer. Follow me for more content like this. Let's connect on Linkedin and X - formerly Twitter

If you have any questions or contributions please drop a comment below. Thank you.

Top comments (0)