0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

サーバー

0
Posted at
// 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);
  });
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?