나아가기

Vue.js + Express로 Memo 앱만들기(4) 본문

Javascript/2022

Vue.js + Express로 Memo 앱만들기(4)

channnnii 2022. 11. 8. 11:41

 +추가를 통해 원하는 메모를 추가하는 기능 만들기 

 

1. frontend 의 MemoView.vue 페이지의 <script> 수정

const add = () => {
      const content = prompt("내용을 입력하세요.");

      //state.data.push("추가된 메모 내용");
      axios.post("./api/memos", { content }).then((res) => {
        state.data = res.data;
      });
    };

 

 

2. backend의 index.js 페이지의 코드 추가 및 수정

app.post("/api/memos", (req, res) => {
    //console.log(req.body);
    memos.push(req.body.content);
    res.send(memos)
});

 

 

※ 에러 발생

 

TypeError: Cannot read properties of undefined (reading 'content')

 

가장 자주 보는 오류 메시지이다. 이 오류는 값이 정의되지 않아 읽을 수 없을 때 발생한다.

    전달된 body 값이 읽을 수 없는 형태이기 때문에 발생하는 이슈다.

    이를 해결하기 위해서는 body의 값을 읽을 수 있는 형태로 파싱(추출)해야 한다.

 

    이 때 사용하는 게 body-parser라는 모듈인데, express 4.x 부터는 내장되어 있어 따로 설치하지 않아도 된다.

// backend index.js 파일에
// 다음의 코드들을 추가해야 한다.
const bodyParser = require("body-parser")

app.use(express.json());

작성한 후, 모듈을 찾을 수 없다는 에러가 발생한다.

따라서 body-parser를 설치해주어야 한다.

npm i body-parser

 

 

다음의 에러를 해결하고 나면, 성공적인 결과 페이지가 뜹니다.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 +만들어진 메모에 대한 수정하는 기능 추가하기 

1. frontend 의 MemoView.vue 페이지의 edit 추가

<template>
  <div class="memo">
    <div class="act">
      <button class="btn btn-primary" @click="add()">+ 추가</button>
    </div>
    <ul>
      <li v-for="(d, idx) in state.data" :key="idx" @click="edit(idx)">
        {{ d }}
      </li>
    </ul>
  </div>
</template>

<script>
 	...
 
    const edit = (idx) => {
      const content = prompt("내용을 입력해 주세요.", state.data[idx]);
      //console.log(content);
      axios.put("/api/memos/" + idx, { content }).then((res) => {
        state.data = res.data;
      });
    };
    
    return { state, add, edit };
     ...
</script>

 

 

2. backend의 index.js 페이지의 코드 추가 및 수정

app.put("/api/memos/:idx", (req, res) => {
    //console.log(req.idx);
    //console.log(req.body);
    memos[req.params.idx] = req.body.content;
    res.send(memos);
});
Comments