Vue.js & MySQL& Express 이용한 데이터 받아오기

dyeon-dev·2023년 9월 16일
0

내가 할 일은 시스템 쪽에서 받아온 데이터 값을 화면에 뿌려주는 것 !!

SQLyog에서 DB 확인

시스템쪽에서 보내준 패킷 값을 백엔드와 프론트엔트 작업을 해주어야 한다.

1. 데이터베이스를 받아올 ts 파일을 생성한 후 연동

backend/database.ts

const mysql = require('mysql');
const connection = mysql.createConnection({
  host: '10.7.12.143',
  port: "3306",
  user: 'root',
  password: 'root',
  database: 'LOG',
});

module.exports = connection;

2. DB 연결

backend/index.ts

import express from "express";

const app = express();
const port = 4000;
const database = require("./database");

app.get("/api/log", (req: express.Request, res: express.Response) => {
  database.query("SELECT * FROM Server_Log", (err: any, data: any) => {
    if (!err) {
      res.send({ data });
      console.log(data)
    } else console.log(err);
  });
});

SELECT * FROM Server_Log라는 쿼리를 직접 입력하고,
에러가 없다면 res에게 data를 전송한다.

데이터는 http://localhost:4000/api/log 에 존재하게 된다.

들어오는 데이터 값

3. axios를 활용해 frontend에서 데이터를 받는다.

frontend/view/LogView.vue

const records = ref<LogType[]>([]);
records.value = [
    {
        time: "2023-09-07T02:58:27.355Z",
        type: "시스템",
        content: "프로그램 시작",
    },
    {
        time: "2023-09-07T02:58:27.355Z",
        type: "시스템",
        content: "프로그램 시작",
    },
    {
        time: "2023-09-07T02:58:27.355Z",
        type: "시스템",
        content:
            "프로그램 시작uuuuuuuuuuuuuuuuuuuuuuuuuuuuu",
    }
];

axios.get('http://localhost:4000/api/log')
        .then((response) => {
            const data = response.data.data
            for (let i = 0; i < data.length; i++) {
                const item = data[i];
                records.value.push({
                    time: item.Time,
                    type: item.Type,
                    content: item.Content,
                });
            }
        })
        .catch((error) => {
            console.error('Error fetching data:', error);
        });
        
 
 <q-table flat square :rows="records" :columns="columns" row-key="time" dense class="table"
                    :rows-per-page-options="[0]" hide-no-data hide-pagination />

axios.get()을 이용해 데이터를 받아온다.
데이터가 있는 곳에서 res의 data를 records의 records.value에 넣어준다.

records와 backend의 records.value 내 변수명들이 같지 않다면 오류가 발생한다.


테이블 형식으로 화면에 뿌려준 패킷 값들 !-!

0개의 댓글