🪢node/node 실습

mern 로그인기능(2)(node실습)[라우팅 분해하기]

하얀성 2024. 2. 20. 11:08
  • req.body는 요청 본문에 포함된 데이터를 다루며, 주로 POST 및 PUT 요청에서 사용됩니다.
  • req.params는 URL 경로에 포함된 매개변수 값을 다루며, 동적 라우팅에서 유용하게 사용됩니다.

윗 코드와 주석모양은 같은 결과를 출력하게 된다.

 

avaScript ES6에서는 객체의 속성 이름과 변수 이름이 같을 때, 속성 이름을 생략할 수 있는 단축 속성명(shorthand property names)을 사용할 수 있습니다

 

// Respond with the note
  res.json({ note });
  //res.json({ note:note });

 

module.exports = {
  fetchNotes,
  fetchNote,
  createNote,
  updateNote,
  deleteNote,
};

// module.exports = {
//   fetchNotes: fetchNotes,
//   fetchNote: fetchNote,
//   createNote: createNote,
//   updateNote: updateNote,
//   deleteNote: deleteNote,
// };

 


객체 구조 분해 할당을 통해서 더 간결한 코드로 수정 가능.

const { title, body } = req.body;
  // const title = req.body.title;
  // const body = req.body.body;

node의 라우팅 분해하기.

 

기존 server.js의 라우팅.

//Routing
app.get("/", (req, res) => {
  res.json({ hello: "world" });
});

app.get("/notes", async (req, res) => {
  //Find the notes
  const notes = await Note.find();
  //Respond the them
  res.json({ notes: notes });
});

app.get("/notes/:id", async (req, res) => {
  // Get id off the url
  const noteId = req.params.id;

  // Find the note using that id
  const note = await Note.findById(noteId);

  // Respond with the note
  res.json({ note: note });
});

app.post("/notes", async (req, res) => {
  //Get the set in data off request body
  const title = req.body.title;
  const body = req.body.body;

  //Create a note with it
  const note = await Note.create({
    title: title,
    body: body,
  });

  //respond with the new note
  res.json({ note: note });
});

app.put("/notes/:id", async (req, res) => {
  //Get the id off the url
  const noteId = req.params.id;

  //Get the data off the req body
  const title = req.body.title;
  const body = req.body.body;

  //Find and update the record
  await Note.findByIdAndUpdate(noteId, {
    title: title,
    body: body,
  });

  //Find updated note(최신 업데이트 내용 반영)
  const note = await Note.findById(noteId);

  // Respond with it(최신 업데이트 내용 반영x)
  res.json({ note: note });
});

app.delete("/notes/:id", async (req, res) => {
  //Get the id off the url
  const noteId = req.params.id;

  //Delete the record
  await Note.deleteOne({ _id: noteId });

  // Respond with it(최신 업데이트 내용 반영x)
  res.json({ success: "Record reload" });
});

//Start our server
app.listen(process.env.PORT);

1. controllers 제작하는 법

-기존 라우팅의 async 이하 부분을 controllers.js로 이동. 

각 함수이름을 지어준다.

-Note 라는 모델 require import문도 함께 옮겨버린다.

 

module.exports = {
  fetchNotes,
  fetchNote,
  createNote,
  updateNote,
  deleteNote,
};

 

2. 기존 라우팅의 뒷부분을 아래처럼 ,notesController exports를 require해와서 대체.

const notesController = require("./controllers/notesController");
 
//Routing
app.get("/notes", notesController.fetchNotes);
app.get("/notes/:id", notesController.fetchNote);
app.post("/notes", notesController.createNote);
app.put("/notes/:id", notesController.updateNote);
app.delete("/notes/:id", notesController.deleteNote);

 

 


https://www.youtube.com/watch?v=jK7mcMrYzj8&list=PL-LRDpVN2fZA-1igOQ6PDcqfBjS-vaC7w&index=1