나아가기

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

Javascript/2022

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

channnnii 2022. 11. 8. 10:50

 backend 파일 생성하기 

 

1. 최상위 파일로 이동해서 mkdir backend 파일 생성하기

mkdir backend

//bakend 파일로 이동한 후, node 모듈 생성
cd backend
npm init

//express 설치
npm install express --save

 

2. backend/index.js 파일을 만들고, 다음의 코드를 작성하기

const express = require('express')
const app = express()
const port = 3000

app.get('/', (req, res) => {
    res.send('Hello World!')
})

app.listen(port, () => {
    console.log(`Example app listening at http://localhost:${port}`)
})

 

3. 실행하기

node index.js

해당 창이 뜬다면, 잘따라한 것!!

 

 

 

 

 

 

 backend 파일과 frontend 파일 연동하기 (1) 

1. backend/index.js에 파일 작성하기

const express = require('express')
const app = express()
const port = 3000

const memos = ["메모 내용 1", "메모 내용 2", "메모 내용 3"];

app.get('/memos', (req, res) => {
    res.send(memos)
});

app.listen(port, () => {
    console.log(`Example app listening at http://localhost:${port}`)
});

 

서버를 다시 실행시키면, 다음과 같은 창이 나옵니다.

 

 

 

 

 

 

 

2. http 요청을 생성하기 위해, frontend 파일에서 axios를 설치합니다.

npm i axios

 

그리고 MemoView 페이지의 <script>부분을 수정합니다.

<script>
import { reactive } from "vue";
import axios from "axios";

export default {
  setup() {
    const state = reactive({
      data: [],
    });

    const add = () => {
      state.data.push("추가된 메모 내용");
    };

    axios.get("http://localhost:3000/memos").then((res) => {
      console.log(res);
    });

    return { state, add };
  },
};
</script>

 

실행을 하면 frontend 창에 아무런 변화가 없고,

개발자 도구를 열어 console을 확인해보면 다음과 같은 문장과 함께 CORS 에러가 납니다.

Access to XMLHttpRequest at 'http://localhost:3000/memos' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

 

구글링을 한 결과, vue.config.js에 proxy 설정!

 

1) frontend에 vue.config.js 파일을 만들고, 다음과 같이 작성

module.exports = {
  devServer: {
    proxy: {
      "/api": {
        target: "http://localhost:3000"
      }
    }
  }
}

 

2) backend의 index.js에서 다음의 코드를 수정합니다.

//수정전
app.get('/memos', (req, res) => {
    res.send(memos)
});


//수정후
app.get('/api/memos', (req, res) => {
    res.send(memos)
});

 

2) frontend의 MemoView.vue에서 <script>의 다음 코드를 추가합니다.

<script>
import { reactive } from "vue";
import axios from "axios";

export default {
  setup() {
    const state = reactive({
      data: [],
    });

    const add = () => {
      state.data.push("추가된 메모 내용");
    };

    axios.get("/api/memos").then((res) => {
      state.data = res.data;
    });

    return { state, add };
  },
};
</script>

 

 

fonrtend를 실행하면 다음의 창이 뜨는 것을 확인할 수 있습니다..!!

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 backend 파일과 frontend 파일 연동하기 (2) 

: (1)에서는 메모 1을 가져왔다면, 이번엔 추가버튼을 눌렀을때 메모가 추가되는 것을 백엔드와 연동 하도록 하겠습니다.

 

1. backend/index.js에서 다음의 코드 작성하기

app.post("/api/memos", (req, res) => {
    memos.push("추가 내용");
    res.send(memos)
});

 

 

 

2. frontend/MemoView.vue 에서 다음의 코드 수정하여 작성하기

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

 

Comments