Skip to content

server.js

  • 기본 라우팅과 파일 업로드
js
const express = require("express");
const multer = require("multer");
const cookieParser = require("cookie-parser");
const { verifyAuth, proxy } = require("./proxy");

const SERVER_POST = 4000;
const UPLOADED_FILE_DIR = "uploaded_files";
const app = express();
const storage = multer.diskStorage({
  destination(req, file, cb) {
    // cb 콜백함수를 통해 전송된 파일 저장 디렉토리 설정
    cb(null, `${UPLOADED_FILE_DIR}/`);
  },
  filename(req, file, cb) {
    // cb 콜백함수를 통해 전송된 파일 이름 설정
    cb(null, file.originalname);
  },
});
const upload = multer({ storage });

app.all("/*", function (req, res, next) {
  res.header("Access-Control-Allow-Origin", "http://local.kakao.com:3000");
  res.header("Access-Control-Allow-Headers", "X-Requested-With");
  res.header("Access-Control-Allow-Credentials", true);
  next();
});

app.use(cookieParser());

app.use("/static", express.static("static"));
app.use("/src", express.static("src"));
app.use(`/${UPLOADED_FILE_DIR}`, express.static(UPLOADED_FILE_DIR));
app.use(`/proxy`, verifyAuth, proxy);

app.get("/", (req, res) => {
  console.log(req.cookies);
  res.send("Hello World!");
});

app.get("/500", (req, res) => {
  res.status(500).send({});
});

// 파일 업로드
app.post("/upload", upload.any(), (req, res) => {
  const name = req.files[0].originalname;
  const url = `http://localhost:${SERVER_POST}/${UPLOADED_FILE_DIR}/${name}`;
  const mimetype = req.get("content-type");

  res.send({
    name,
    url,
    mimetype,
  });
});

app.listen(SERVER_POST, () => {
  console.log(`Example app listening on port ${SERVER_POST}!`);
});

proxy.js

  • BackEnd For FrontEnd를 위한 Proxy
js
const {
  createProxyMiddleware,
  fixRequestBody,
  responseInterceptor,
} = require("http-proxy-middleware");

module.exports = {
  verifyAuth: (req, res, next) => {
    console.log("인증/인가 처리");

    next();
  },
  proxy: (req, res, next) => {
    createProxyMiddleware({
      target: "https://the-next-web-research-lab.github.io",
      pathRewrite: { [`^/proxy`]: "" },
      changeOrigin: true,
      timeout: 1000 * 5,
      onProxyReq: fixRequestBody,
      onProxyRes: responseInterceptor(async (responseBuffer) => responseBuffer),
      selfHandleResponse: true,
    })(req, res, next);
  },
};

index.html

html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Title</title>
  </head>
  <body>
    <input
      type="file"
      id="my-file"
    />
    <input
      type="button"
      value="Submit"
      onclick="uploadFile()"
    />

    <script src="/src/sample.js"></script>
    <script>
      console.log(add(10, 5));

      const uploadFile = async () => {
        const file = document.querySelector("#my-file").files[0];
        const formData = new FormData();

        formData.append("uploadFile", file, file.name);

        const response = await fetch("/upload", {
          method: "POST",
          body: formData,
        });

        console.log(await response.json());
      };

      const proxyTest = async () => {
        const PROXY_URL = "http://localhost:4000/proxy";
        const response = await fetch(`${PROXY_URL}/intro.html`);
        const text = await response.text();

        console.assert(text.includes("더넥스트웹리서치랩"));
      };

      proxyTest();
    </script>
  </body>
</html>

sample.js

js
const add = (a, b) => a + b