Start learning free

LESSON 13 OF 173 · BACKEND: YOUR FIRST API

Your First Route

Practice

A web server is a program that waits for requests and answers them. A browser, or any other program, sends a request: a method, like GET ("give me"), and a path, like / or /products. The server sends back a response: a status code that says how it went, and a body.

In Express, the line const app = express(); creates your app, and a route teaches it to answer a path. A route is a call to app.get with a path and a function:

app.get("/hello", (req: Request, res: Response) => {
  res.send("Hi there!");
});

When a GET request for /hello arrives, Express calls the function with req, the request, and res, the response. The types Request and Response come from the first line of the file, import express, { Request, Response } from "express";. res.send sends the text back, with the status 200, which means OK. A path that no route matches gets 404 Not Found, with Express's own HTML error page.

Your app must answer:

GET /          →  200  Welcome to the shop!
GET /products  →  404  (an HTML error page)

Your task: the app is already created for you. Add a route for the path / whose function takes req: Request and res: Response and answers with the text "Welcome to the shop!".


Assignment
Follow the Coding Tutorial to write the shop's first route, GET /, and the function that answers it.


Hint
In app.get, the path comes first, as a string, then the arrow function with its two typed parameters. The res.send line goes inside the function's braces.


STEP 1 OF 2
    Ctrl + Enter to check