server 폴더 구조

Creating the dots·2021년 11월 14일
0

project-2-느린우체통

목록 보기
7/10

폴더를 구분해서 작성해주는 과정에서 실수가 생겨 404 에러가 났다. 그래서 좀 더 확실히 정리하기 위해 server의 폴더와 파일 구조를 tree를 설치해 확인해보면서 정리해보려고 한다.

tree

//tree 설치
sudo apt-get install tree

//구조화할 폴더로 이동해서 3 depth까지(-L)
//node_modules와 test 폴더를 제외하고(-I) 구조화해 표현한다.
tree -L 3 -I "node_modules|test"

client axios 요청

  useEffect(() => {
    const fetchPosts = async () => {
      setLoading(true);
      const res = await axios.get(
        `http://localhost:8080/mails/posts?page=${currentPage}&limit=${postsPerPage}`
      );
      setPosts(res.data);
      setLoading(false);
      console.log(res.data);
    };
    fetchPosts();
  }, []);

server: ./index.js

  • "/mails"로 들어온 요청은 postsRouter로 보낸다. (첫번째 폴더 분기)
const express = require("express");
const app = express();
const cors = require("cors");

const postsRouter = require("./router/postsRouter");

app.use(express.json({ strict: false }));

app.use(
  cors({
    origin: "http://localhost:3001",
    credentials: true,
    methods: ["GET", "HEAD", "PUT", "PATCH", "POST", "DELETE", "OPTIONS"],
  })
);
app.use("/mails", postsRouter);

const PORT = 8080;

let server = app.listen(PORT, () =>
  console.log(`🚀 Server is starting on ${PORT}`)
);

module.exports = server;

server: router/postsRouter.js

  • /mails로 들어온 요청들 중에서 /posts 요청은 controllers 폴더 내 mail 폴더 내 posts.js의 함수를 동작시킨다.
const express = require("express");
const router = express.Router();
const { posts } = require("../controllers/mails");

router.get("/posts", posts);

module.exports = router;

server: controllers/mails/posts.js

module.exports = async (req, res) => {
  const page = req.query.page;
  const limit = req.query.limit;
  const startIndex = (page - 1) * limit;
  const endIndex = page * limit;
  const resultPosts = postData.slice(startIndex, endIndex);
  res.json(resultPosts);
};

reference

profile
어제보다 나은 오늘을 만드는 중

0개의 댓글