CodeBlanks Logo Icon CodeBlanks

Express app

Set up the API skeleton with an Express app.

The Express app

The second lesson sets up the Express app. Express is the most popular web framework for Node.js. You create an app with const express = require("express"); const app = express();.

To define a route you use app.get(path, handler). For example app.get("/", (req, res) => res.json({ status: "ok" })) sends a JSON response to the root path. req is the request and res is the response. res.json() turns an object into JSON and sends the response. To start the server you call app.listen(port, cb). In this lesson we add the root route and verify the API is alive.

Responding with res.json

res.json(data) turns data into a JSON string and sends the response. The content type is automatically application/json. This is the most common response method in APIs.

For example res.json({ status: "ok" }) produces the response {"status":"ok"}. You could use res.send() too, but for JSON res.json is better because it handles the content type and serialization automatically. In this lesson the GET / route returns { status: "ok" } so we can see the API is alive. In later lessons we return real data with a /books route.

Practice Define the root route

Define a GET "/" route. The handler should return the object { status: "ok" } as JSON with res.json. The self-request part is already in the starting code.

Starter code

index.js
const books = [];
books.push({ id: 1, title: "Node.js" });

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

// GET "/" route — send { status: "ok" } JSON response
// write here

// Self-request (boilerplate)
const server = app.listen(3000, () => {
  const http = require("http");
  http.get("http://localhost:3000/", (res) => {
    let body = "";
    res.on("data", (c) => body += c);
    res.on("end", () => { console.log(body); server.close(); });
  });
});

Sample solution

index.js
app.get("/", (req, res) => {
  res.json({ status: "ok" });
});

Expected output

{"status":"ok"}

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Complete the GET route

Question
app.____("/", (req, res) => { res.json({ status: "ok" }); });
Answer
app.get("/", (req, res) => { res.json({ status: "ok" }); });

Explanation: app.get defines a GET route.

2 Match each piece to its role

Term Meaning
express Web framework
app.get Defines a GET route
res.json Sends a JSON response
app.listen Starts the server

3 Which HTTP method does app.get handle in Express?

index.js
app.get("/", handler)
  • POST
  • GET Correct answer
  • DELETE
  • PUT

Explanation: app.get handles only GET requests.

All lessons in Intermediate