iT邦幫忙

2025 iThome 鐵人賽

DAY 29
0
Vue.js

Vue 新手學習紀錄系列 第 29

Day 29|Vue 串接資料庫

  • 分享至 

  • xImage
  •  

拖到最後要來還債了qq 來寫連接資料庫的部分
Step1: 建立 server 資料夾
這裡是用 postgres

mkdir server
cd server
npm init -y
npm install express cors pg

Step2: 設定連線資料

import express from 'express'
import cors from 'cors'
import pkg from 'pg'

const { Pool } = pkg
const app = express()

app.use(cors())
app.use(express.json())

const pool = new Pool({
  user: '你的user',
  password: '你的password',
  host: '你的host',
  port: 你的port,
  database: '你的dbname'
})

app.get('/api/test', async (req, res) => {
  try {
    const result = await pool.query('SELECT NOW()')
    res.json({ success: true, time: result.rows[0] })
  } catch (err) {
    console.error(err)
    res.status(500).json({ success: false, message: '資料庫連線失敗' })
  }
})

const PORT = 3000
app.listen(PORT, () => console.log(`🚀 Server running on port ${PORT}`))

但這邊暫時沒連成功,好像少了一個變數,拿到之後再試試看qaq

Step3: 從資料庫中撈資料

app.get('/api/posts', async (req, res) => {
  try {
    const result = await pool.query('SELECT * FROM posts ORDER BY id DESC')
    res.json(result.rows)
  } catch (err) {
    res.status(500).json({ message: err.message })
  }
})

Step4: 呼叫 API

import { ref, onMounted } from 'vue'
import axios from 'axios'

export function usePosts() {
  const posts = ref([])
  const loading = ref(false)
  const error = ref(null)

  async function fetchPosts() {
    loading.value = true
    try {
      const res = await axios.get('http://localhost:3000/api/posts')
      posts.value = res.data
    } catch (err) {
      error.value = err.message
    } finally {
      loading.value = false
    }
  }

  onMounted(fetchPosts)

  return { posts, loading, error, fetchPosts }
}

最後最後連線資訊要放到 .env 中,避免被看光光


上一篇
Day 28 | Vue Suspense 實現 loading 狀態
下一篇
Day 30 | 來寫寫第一次參加鐵人賽的心得
系列文
Vue 新手學習紀錄30
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言