Getting started with Express

Getting started with Express

In the words of its authors - Express is a "Fast, unopinionated, minimalist web framework for Node.js". It is also one of the most popular Node.js web frameworks.

So you want to set up an Express server, this article will help you do just that.

Prerequisites

Local machine

To set up an Express server, you will need NodeJS and npm installed on your machine. After successful installation of node and npm, create a folder and run :

npm init

This is a utility that will help you create a package.json file. This file will hold all the metadata about your project like name, versioning, dependencies, etc. You can learn more about this in the official nodejs docs.

Preconfigured Online IDEs

You can skip the above setup and directly use online IDEs. I have linked a Repl at the end of the article where you can find the full code.

Installing Express

The express package needs to be installed to run the express server.

npm install express

This command installs the express npm package. For Repl, you may just import the package in the index.js file.

Express code

Boilerplate

const express = require('express');

const app = express();

app.get('/', (req, res) => {
  res.send('My express app');
});

const PORT = 3000;
app.listen(PORT, () => {
  console.log('server started at PORT: ', PORT);
});

This is the basic code required to start an express server. To send JSON data do the following :

app.get('/', (req, res) => {
  res.json({success: true, message: "Express server connected"});
});

body-parser

This package helps in parsing incoming request bodies in a middleware before your handlers, available under the req.body property.

This helps in sending JSON bodies to the server required in a POST API call.

Routing

To make the code clean and modular we can make use of express routers. As an example, we will create a category router. In the routers/categories.router.js file add the following code :

const express = require("express");
const router = express.Router();

let categories = [
  {id: 1, name: "Cat 1"},
  {id: 2, name: "Cat 2"},
  {id: 3, name: "Cat 3"}
]

router.route("/")
  .get(async (req, res) => {
    try {
      res.json({ success: true, categories })
    } catch (error) {
      res.status(500).json({ success: false, message: "Unable to get categories", errorMessage: error.message });
    }
  }).post(async (req, res) => {
    try {
      const category = req.body;
      categories = [...categories, category];
      res.json({ success: true, categories });
    }
    catch (error) {
      res.status(500).json({ success: false, message: "Unable to create category", errorMessage: error.message });
    }
  })

module.exports = router;

Here we are making use of an array, in projects, this is replaced by databases like MongoDB.

After the above changes, our index.js file looks like this -

const express = require("express");
const bodyParser = require("body-parser");

const app = express();
app.use(bodyParser.json());

const categoryRouter = require("./routers/categories.router");
app.use("/category", categoryRouter);

app.get('/', (req, res) => {
  res.json({success: true, message: "Express server"});
});

const PORT = 3000;
app.listen(PORT, () => {
  console.log('server started at PORT: ', PORT);
});

In the above code, we have imported the category router, all the routes defined under this router will be preceded by /category. So the category GET API call will be https://localhost:3000/category, in your local machine.

The browser will show the following result on the page -

expresseg1.png

You can check out this Repl to find the full code and fork it to customize it to your needs.

Hope this article helped you in getting started with Express. To explore more check out these links -

  1. Express Routing
  2. Express Middleware

These will help you understand routing methods, parameters, and express middleware.