2021년 2월 5일 복기(TIL Server)

https://nodejs.org/ko/docs/guides/anatomy-of-an-http-transaction/

이걸 많이 봐야한단다.

우리의 유투브 선생님

https://www.youtube.com/watch?v=wxbQP1LMZsw

Boom

https://www.youtube.com/watch?v=UMKS6su8HQc

/// A BASIC Node server

const http = require("http");

const server = http.createServer(function (req, res) {
  res.setHeader("Content-type", "application/json");
  res.setHeader("Access-Control-Allow-Origin", "*");

  res.writeHead(200); /// status code HTTP 200/ OK

  let dataObj = { id: 123, name: "Bob", email: "[email protected]" };
  let data = JSON.stringify(dataObj);
  res.end(data);
});

server.listen(1234, function () {
  console.log("Listneing on port 1234");
});

그래 이건 알겠어 근데 CORS는 뭐야?

https://developer.mozilla.org/ko/docs/Web/HTTP/CORS

PREFLIGHT REQUEST

https://www.youtube.com/watch?v=Ka8vG5miErk

YOUTUBE

https://www.youtube.com/watch?v=0IMz8d9Cby4

https://0oooceanhigh.medium.com/request-on-f060659cb36e

SERVER ERROR

https://developer.mozilla.org/en-US/docs/Web/HTTP/Status

const http = require("http");

const PORT = 5000;

const ip = "localhost";

const server = http.createServer((request, response) => {
  const { method, url } = request; // 편하게 구조분해할당
  let body = [];
  if (method === "OPTIONS") {
    response.writeHead(200, defaultCorsHeader);
    response.end();
  }
  if (method === "POST" && url === "/upper") {
    request
      .on("error", (err) => {
        console.error(err);
      })
      .on("data", (chunk) => {
        body.push(chunk);
      })
      .on("end", () => {
        body = Buffer.concat(body).toString();
        console.log(body.toUpperCase());
        response.writeHead(201, defaultCorsHeader);
        response.end(JSON.stringify(body.toUpperCase()));
      });
  }
  if (method === "POST" && url === "/lower") {
    request
      .on("error", (err) => {
        console.error(err);
      })
      .on("data", (chunk) => {
        body.push(chunk);
      })
      .on("end", () => {
        body = Buffer.concat(body).toString();
        response.writeHead(201, defaultCorsHeader);
        response.end(JSON.stringify(body.toLowerCase()));
      });
  } else {
    response.writeHead(404, defaultCorsHeader);
    response.end();
  }
});

server.listen(PORT, ip, () => {
  console.log(`http server listen on ${ip}:${PORT}`);
});

const defaultCorsHeader = {
  "Access-Control-Allow-Origin": "*",
  "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS",
  "Access-Control-Allow-Headers": "Content-Type, Accept",
  "Access-Control-Max-Age": 10,
};

좋은 웹페이지 즐겨찾기