Node.js
Summary - HTTP server
Combine createServer, routing and JSON to write an API.
Summary - HTTP server
In this group you learned the core tools of an HTTP server: setting up a server with createServer, handling request and response with req and res, routing with req.url, sending JSON responses with JSON.stringify and parsing query strings with new URL.
Now you will combine them into a small API. The API will return a JSON response to the /api path and a different JSON to other paths. This mini task shows how routing and JSON combine in a real API.
API design
The API skeleton: a createServer handler, routing with req.url and JSON response with JSON.stringify. The /api path gets a known JSON; other paths get a different JSON.
Flow: const server = http.createServer((req, res) => { res.setHeader("Content-Type", "application/json"); if (req.url === "/api") { res.end(JSON.stringify({ status: "ok" })); } else { res.end(JSON.stringify({ status: "none" })); } });. A /api request gets {"status":"ok"}; another path gets {"status":"none"}. The content type is set to application/json, so the client parses the response safely.
Exercise Write an API
Import the http module. Create a server with createServer. Inside the handler call res.setHeader("Content-Type", "application/json"). If req.url === "/api" call res.end(JSON.stringify({ status: "ok" })), otherwise res.end(JSON.stringify({ status: "none" })). The ready-made code below sends a request to /api.
Show example solution
const http = require("http");
const server = http.createServer((req, res) => {
res.setHeader("Content-Type", "application/json");
if (req.url === "/api") { res.end(JSON.stringify({ status: "ok" })); }
else { res.end(JSON.stringify({ status: "none" })); }
});
server.listen(3000, () => {
http.get("http://localhost:3000/api", (res) => {
let body = "";
res.on("data", (c) => body += c);
res.on("end", () => { console.log("Reply: " + body); server.close(); });
});
});
Test yourself
-
What pieces does the API combine?
if (req.url === "/api") { res.end(JSON.stringify(...)); }
- Only createServer
- createServer, routing ve JSON
- Only require
- Only console.log
Show answer
createServer, routing ve JSON — createServer + routing (req.url) + JSON (JSON.stringify) combine.
-
Match each tool to its role
- createServer
- Creates the server
- req.url
- Does routing
- JSON.stringify
- Produces JSON response
- setHeader
- Sets content type
Next lesson: Module design