Summary - HTTP server
- Node.js course
- Intermediate
- Lesson 18/116
- 5 min
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.
Practice 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.
Starter code
// Import the http module and create a server
// write here
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(); });
});
});Sample 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(); });
});
});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 API combine?
if (req.url === "/api") { res.end(JSON.stringify(...)); }- Only createServer
- createServer, routing ve JSON Correct answer
- Only require
- Only console.log
Explanation: createServer + routing (req.url) + JSON (JSON.stringify) combine.
2 Match each tool to its role
| Term | Meaning |
|---|---|
createServer |
Creates the server |
req.url |
Does routing |
JSON.stringify |
Produces JSON response |
setHeader |
Sets content type |