Node.js bisa membuat web server tanpa framework apapun.
Server paling sederhana:
import http from "http";
const server = http.createServer((req, res) => {
res.writeHead(200, { "Content-Type": "text/plain" });
res.end("Halo dari Node.js!");
});
server.listen(3000, () => {
console.log("Server berjalan di http://localhost:3000");
});
Membaca URL dan method:
const server = http.createServer((req, res) => {
const { method, url } = req;
if (method === "GET" && url === "/") {
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify({ message: "Hello!" }));
} else if (method === "GET" && url === "/users") {
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify({ users: ["Budi", "Siti"] }));
} else {
res.writeHead(404);
res.end("Not Found");
}
});
Masalah: Kode ini akan sangat panjang untuk banyak route. Solusi? Express.js!