๐ฏ ํ์ต ๋ชฉํ
- ํ๋ก ํธ(Vue)์ ๋ฐฑ์๋(Express)๋ฅผ ์์ ํ ๋ถ๋ฆฌํ์ฌ ๊ฐ๋ฐ
- CORS ๋ฌธ์ ํด๊ฒฐ๊ณผ ํ๋ก์ ์ค์ ์ ์ฉ
- ๋ฐฐํฌ ์ API ๊ฒฝ๋ก ์ ๋ฆฌ
โ 1. ํ์ฌ ๊ตฌ์กฐ ์์ฝ
- ํ๋ก ํธ์๋(Vue CLI ์ฑ):
localhost:8080 - ๋ฐฑ์๋ ์๋ฒ(Express):
localhost:3000
โ ์๋ก ๋ค๋ฅธ ํฌํธ๋ก ์ธํด CORS ์ ์ฑ ์๋ฐ ๋ฐ์ ๊ฐ๋ฅ
โ 2. ๋ฐฑ์๋์์ CORS ํ์ฉ
ํฐ๋ฏธ๋์์ Express ์๋ฒ ๋๋ ํ ๋ฆฌ๋ก ์ด๋ํ ๋ค ๋ค์์ ์คํํ์ธ์:
npm install cors
๐ ์: vue2-api/ ์์์ ์คํ
โ
์๋ฒ ์ฝ๋ (server.js)
const express = require('express')
const cors = require('cors')
const app = express()
app.use(cors()) // ๋ชจ๋ ์ถ์ฒ ํ์ฉ
app.use(express.json())
// ๋๋จธ์ง ๋ผ์ฐํฐ ์ค์ ...
๋ณด์ ๊ฐํ๋ฅผ ์ํด ๋ฐฐํฌ ์์๋ ๋ค์๊ณผ ๊ฐ์ด ์ ํ๋ ์ถ์ฒ๋ง ํ์ฉํ ์ ์์ต๋๋ค:
app.use(cors({ origin: 'https://my-frontend-domain.com' }))
โ 3. ํ๋ก ํธ์๋ ํ๋ก์ ์ค์ (Vue CLI ์ ์ฉ)
๐ vue.config.js ์์
// vue.config.js
module.exports = {
devServer: {
proxy: {
'/api': {
target: 'http://localhost:3000',
changeOrigin: true,
pathRewrite: { '^/api': '' }
}
}
}
}
โ Axios ์์ฒญ ๊ฒฝ๋ก ๋ณ๊ฒฝ
ํ๋ก ํธ์์ ๊ธฐ์กด:
const API_URL = 'http://localhost:3000/todos'
๋ณ๊ฒฝ ํ:
const API_URL = '/api/todos' // ํ๋ก์๋ฅผ ํตํด ์๋ฒ๋ก ์ ๋ฌ๋จ
์ด ์ค์ ์ ํตํด Vue ์ฑ์ CORS ์์ด /api/todos๋ก ๋ฐฑ์๋์ ํต์ ํ ์ ์์ต๋๋ค.
โ 4. ํ๋ก์ ํธ ์คํ
# ํฐ๋ฏธ๋ 1
node server.js
# ํฐ๋ฏธ๋ 2 (vue ํ๋ก์ ํธ ํด๋)
npm run serve
ํ๋ก ํธ ์์ฒญ: localhost:8080/api/todos
๋ฐฑ์๋ ์๋ต:
localhost:3000/todosโ ํ๋ก์๊ฐ ์ค๊ฐ์์ ์ฐ๊ฒฐ
โ 5. ๋ฐฐํฌ ์ ๊ตฌ์กฐ
| ๊ตฌ์ฑ | ์์ |
|---|---|
| ํ๋ก ํธ | Netlify, Vercel, GitHub Pages, ์ ์ ํธ์คํ |
| ๋ฐฑ์๋ | Render, Heroku, Railway, EC2 ๋ฑ ์๋ฒ ํธ์คํ |
| API ๊ฒฝ๋ก | ํ๋ก์ ๋์ ๋๋ฉ์ธ ์ฃผ์ ์ง์ ์ง์ ํ์ |
// ๋ฐฐํฌ ์ Axios baseURL ์์
const API_URL = 'https://my-api-server.com/todos'
๐ง ์ ๋ฆฌ
| ํญ๋ชฉ | ์ค๋ช |
|---|---|
| CORS ํ์ฉ | ์๋ฒ์์ cors() ์ฌ์ฉ |
| ํ๋ก์ ์ค์ | ๊ฐ๋ฐํ๊ฒฝ์์ CORS ์ฐํ์ฉ (vue.config.js) |
๊ฒฝ๋ก /api/... |
์ค์ ์๋ฒ์์๋ /todos, Vue์์๋ /api/todos |
| ๋ฐฐํฌ ์ | ํ๋ก์ ์ ๊ฑฐํ๊ณ ์ ๋ URL ์ฌ์ฉ |
FE ์ ์ฅ์
GitHub - heroyooi/vue2-app at ch9
BE ์ ์ฅ์
๐ฌ ๋๊ธ
โป ๋ก๊ทธ์ธ ํ ๋๊ธ์ ์์ฑํ ์ ์์ต๋๋ค.