// server.js
const http = require("http");
const { URL } = require("url");
const routes = {
"GET /": homeHandler,
"GET /users": usersHandler,
"POST /users": createUserHandler,
};
const server = http.createServer(async (req, res) => {
try {
const url = new URL(req.url, `http://${req.headers.host}`);
const key = `${req.method} ${url.pathname}`;
const handler = routes[key];
if (!handler) {
return sendJson(res, 404, { message: "Not Found" });
}
await handler(req, res, url);
} catch (error) {
console.error(error);
sendJson(res, 500, { message: "Internal Server Error" });
}
});
server.listen(3000, () => {
console.log("Server running at http://localhost:3000");
});
// ===== handlers =====
function homeHandler(req, res) {
sendJson(res, 200, { message: "Hello Node.js" });
}
function usersHandler(req, res) {
sendJson(res, 200, [
{ id: 1, name: "Taro" },
{ id: 2, name: "Jiro" },
]);
}
async function createUserHandler(req, res) {
const body = await readJsonBody(req);
sendJson(res, 201, {
message: "User created",
user: body,
});
}
// ===== utilities =====
function sendJson(res, statusCode, data) {
res.writeHead(statusCode, {
"Content-Type": "application/json; charset=utf-8",
});
res.end(JSON.stringify(data));
}
function readJsonBody(req) {
return new Promise((resolve, reject) => {
let body = "";
req.on("data", chunk => {
body += chunk;
// 大きすぎるリクエストを防ぐ
if (body.length > 1_000_000) {
req.destroy();
reject(new Error("Request body too large"));
}
});
req.on("end", () => {
try {
resolve(body ? JSON.parse(body) : {});
} catch {
reject(new Error("Invalid JSON"));
}
});
req.on("error", reject);
});
}
Register as a new user and use Qiita more conveniently
- You get articles that match your needs
- You can efficiently read back useful information
- You can use dark theme