Javascript/2022

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

channnnii 2022. 11. 8. 13:43

 express + mysql 연동하기 

 

1. Mysql 설치 및 스키마 만들기

 - Memo 스키마에 memos 테이블 만들어주기.

 - 테이블에 id와 content 컬럼 만들어주기.

 

 

 

 

2. backend에 mysql 모듈 설치하기 및 코드 작성하기

 

1) backend에 mysql모듈 설치하기.

npm install mysql

 

2) backend에 database.js 파일을 만들고, 코드 작성하기

const mysql = require('mysql');

const con = mysql.createConnection({
  host: "localhost",
  user: "root",
  password: "1234",
  database: "memo"
});

module.exports = {
    async run(query){
        return new Promise((reslove) => {
            con.query(query, (error, rows) => {
                if (error) throw error;
                reslove(rows);
            });
        });
    }
}

 

3) database.js 파일을 사용하기 위해, index.js 파일에 import 해주기

const database = require("./database");

 

 

 

3. backend에 index.js 파일과 frontend에 MemoView.vue  코드 작성하기

 

1) DB 데이터 가져오기_ backend/index.js

//db안에 데이타 가져오기
app.get('/api/memos', async (req, res) => {
    const result = await database.run("SELECT * FROM memos");
    res.send(result);
});

 

 

2) DB에 데이터 작성 후 추가하기

 

① backend/index.js

app.post("/api/memos", async (req, res) => {
    //console.log(req.body);
    await database.run(`INSERT INTO memos (content) VALUES ('${req.body.content}')`);
    const result = await database.run("SELECT * FROM memos");
    res.send(result);
});

 

② frontend/MemoView.vue

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

      if (!content) {
        alert("내용을 입력해주세요.");
        return add();
      }
      //state.data.push("추가된 메모 내용");
      axios.post("./api/memos", { content }).then((res) => {
        state.data = res.data;
      });
    };

 

 

3) DB에 데이터 수정하기

 

① frontend/MemoView.vue

<template>
	...
    <ul>
      <li v-for="d in state.data" :key="d.id" @click="edit(d.id)">
        {{ d.content }}
      </li>
    </ul>
	...
</template>

- 템플렛에 li 수정!!

 

② backend/index.js

app.put("/api/memos/:id", async (req, res) => {
    await database.run(`UPDATE memos SET content = '${req.body.content}' WHERE id = ${req.params.id}`);
    const result = await database.run("SELECT * FROM memos");
    res.send(result);
});

 

③ frontend/MemoView.vue

const edit = (id) => {
      const content = prompt(
        "내용을 입력해 주세요.",
        state.data.find((d) => d.id === id).content
      );
      //console.log(content);
      axios.put("/api/memos/" + id, { content }).then((res) => {
        state.data = res.data;
      });
    };