Node.js
Express API
Set up the REST API skeleton with Express.
User routes
In this lesson we add two routes for the /users resource: GET /users returns the user list, POST /users creates a new user. In Express app.get and app.post are separate methods; they register different handlers for the same path.
In handlers res.json(data) sends the response as JSON. GET /users can return an empty array []; POST /users can return {created: true}. You also add each route to the array with routes.push(...). Then routes.map(r => r.method + ' ' + r.path).join(', ') prints the routes as one string. This is a clean way to summarize the API surface.
Printing the routes
To print all routes as one string you use routes.map(...).join(', '). map turns each route into a string; join combines them with a comma. This summarizes the API surface.
Example: routes.map(r => r.method + ' ' + r.path).join(', '). With three routes the output is GET /health, GET /users, POST /users. join(', ') places a comma and space between items. This is a practical way to inspect routes within the program. console.log('Routes: ' + ...) adds a label prefix.
Exercise Add the user routes
Add app.get('/users', (req, res) => res.json([])). Record it with routes.push({method: 'GET', path: '/users'}). Add app.post('/users', (req, res) => res.json({created: true})). Record with routes.push({method: 'POST', path: '/users'}). Print console.log('Routes: ' + routes.map(r => r.method + ' ' + r.path).join(', ')).
Show example solution
const express = require('express');
const app = express();
const routes = [];
app.get('/health', (req, res) => res.json({ok: true}));
routes.push({method: 'GET', path: '/health'});
console.log('Server ready');
app.get('/users', (req, res) => res.json([]));
routes.push({method: 'GET', path: '/users'});
app.post('/users', (req, res) => res.json({created: true}));
routes.push({method: 'POST', path: '/users'});
console.log('Routes: ' + routes.map(r => r.method + ' ' + r.path).join(', '));
Test yourself
-
Define the GET route
app.____('/users', (req, res) => res.json([]));
Show answer
app.get('/users', (req, res) => res.json([]));
-
Match each piece to its role
- app.get
- Registers a GET route
- app.post
- Registers a POST route
- res.json
- Sends a JSON response
- .map
- Transforms each item
-
What does routes.map(r => r.method + ' ' + r.path) produce?
routes.map(r => r.method + ' ' + r.path)
- Yol dizesi dizisi
- An array of numbers
- Boole dizisi
- Bir promise
Show answer
Yol dizesi dizisi — map turns each route into a 'METHOD path' string.
Next lesson: fs persistence