Summary - Express basics
- Node.js course
- Intermediate
- Lesson 29/116
- 5 min
Combine express, app.get and app.listen to write an API.
Summary - Express basics
In this group you learned the core tools of Express: creating an application with express(), defining GET routes with app.get, defining POST routes with app.post and starting the server with app.listen.
Now you will combine them into a small API. The API will return a JSON response to the /api path. This mini task shows how Express's core tools combine in a real API.
API design
The API skeleton: an application with express(), a route with app.get and a server with app.listen. The /api path gets a JSON response.
Flow: const app = express(); app.get("/api", (req, res) => res.json({ status: "ok" })); app.listen(3000, () => console.log("Server started"));. A /api request gets {"status":"ok"}. res.json sends an object as a JSON response; the content type is set automatically. Express lets you do this with far shorter code than the http module.
Practice Write an Express API
Import express and create app. Define a route with app.get("/api", (req, res) => res.json({ status: "ok" })). The ready-made code below starts the server and sends a request to /api.
Starter code
// Import express and create app
// write here
// Respond with JSON to the "/api" route
// write here
const server = app.listen(3000, () => {
const http = require("http");
http.get("http://localhost:3000/api", (res) => {
let body = "";
res.on("data", (c) => body += c);
res.on("end", () => { console.log("Reply: " + body); server.close(); });
});
});Sample solution
const express = require("express");
const app = express();
app.get("/api", (req, res) => res.json({ status: "ok" }));
const server = app.listen(3000, () => {
const http = require("http");
http.get("http://localhost:3000/api", (res) => {
let body = "";
res.on("data", (c) => body += c);
res.on("end", () => { console.log("Reply: " + body); server.close(); });
});
});Expected output
Yanıt: {"durum":"ok"}
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What pieces does the Express API combine?
app.get('/api', (req, res) => res.json(...))- express(), app.get ve app.listen Correct answer
- Only require
- Only console.log
- Only res.send
Explanation: express() + app.get + app.listen combine.
2 Match each tool to its role
| Term | Meaning |
|---|---|
express() |
Creates the application |
app.get |
Defines a route |
res.json |
Sends a JSON response |
app.listen |
Starts the server |