無法使用 postgres 和 nodeJS 檢索數據
P粉445714413
P粉445714413 2024-04-03 11:13:03
0
1
421

這是我設定以下文件的方法: 索引.js

const express = require('express')

const app = express()

const port = 8000
const expense_model = require('./expense_model')

app.use(express.json());
app.use(function (req, res, next) {
    res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8000');
    res.setHeader('Access-Control-Allow-Methods', 'GET,POST,PUT,DELETE,OPTIONS');
    res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Access-Control-Allow-Headers');
    next();
  });

  app.get('/', (req, res) => {
    expense_model.getExpenses()
      .then(expenses => {
        res.status(200).json(expenses);
      })
      .catch(error => {
        console.error('Failed to retrieve expenses:', error);
        res.status(500).json({ error: 'Failed to retrieve expenses' });
      });
  });
  
  app.post('/expenses', (req, res) => {
    expense_model.createExpense(req.body)
    .then(response => {
      res.status(200).send(response);
    })
    .catch(error => {
      res.status(500).send(error);
    })
  })
  app.delete('/expenses/:id', (req, res) => {
    expense_model.deleteExpense(req.params.id)
    .then(response => {
      res.status(200).send(response);
    })
    .catch(error => {
      res.status(500).send(error);
    })
  })



app.listen(port, () => console.log(`Example app listening on port ${port}!`))

和expense_model.js

#
const Pool = require('pg').Pool
const pool = new Pool({
    user: 'my_user',
    host: 'localhost',
    database: 'my_database',
    password: 'root',
    port: 5432,
  });
 
  async function getExpenses(req, res) {
    try {
      const query = 'SELECT * FROM expenses';
      const result = await pool.query(query);
  
      const expenses = result.rows;
  
      res.status(200).json(expenses);
      console.log('Response:', res);
    } catch (err) {
      console.error('Failed to retrieve expenses:', err);
      res.status(500).json({ error: 'Failed to retrieve expenses' });
    }
  }
  
  
  
  async function createExpense(req, res) {
    const { expense, amount, description, tag } = req.body;
    const query = 'INSERT INTO expenses (expense, amount, description, tag) VALUES (, , , ) RETURNING *';
    const values = [expense, amount, description, tag];
  
    try {
      const result = await pool.query(query, values);
      res.status(201).json(result.rows[0]);
    } catch (err) {
      console.error('Failed to create an expense:', err);
      res.status(500).json({ error: 'Failed to create an expense' });
    }
  }
  
 
  async function updateExpense(req, res) {
    const id = parseInt(req.params.id);
    const { expense, amount, description, tag } = req.body;
    const query = 'UPDATE expenses SET expense = , amount = , description = , tag =  WHERE id = ';
    const values = [expense, amount, description, tag, id];
  
    try {
      const result = await pool.query(query, values);
      if (result.rowCount === 0) {
        res.status(404).json({ error: 'Expense not found' });
      } else {
        res.json({ message: 'Expense updated successfully' });
      }
    } catch (err) {
      console.error('Failed to update an expense:', err);
      res.status(500).json({ error: 'Failed to update an expense' });
    }
  }
  
  
  async function deleteExpense(req, res) {
    const id = parseInt(req.params.id);
    const query = 'DELETE FROM expenses WHERE id = ';
    const values = [id];
  
    try {
      const result = await pool.query(query, values);
      if (result.rowCount === 0) {
        res.status(404).json({ error: 'Expense not found' });
      } else {
        res.json({ message: 'Expense deleted successfully' });
      }
    } catch (err) {
      console.error('Failed to delete an expense:', err);
      res.status(500).json({ error: 'Failed to delete an expense' });
    }
  }
  
  module.exports = {
    getExpenses,
    createExpense,
    deleteExpense,
    updateExpense
  }

我收到錯誤無法檢索費用:TypeError:無法讀取未定義的屬性(讀取「json」) 在 Object.getExpenses ,在前端提交表單時,我也收到 axios 錯誤。 問題可能出在 postgres 連接方式。這是我第一次使用 postreSQL,所以我不太熟悉它。

P粉445714413
P粉445714413

全部回覆(1)
P粉066725148

好吧,所以我沒有正確呼叫該函數, 應該是這樣的: app.get('/',expense_model.getExpenses); 在我的原始程式碼中,我呼叫了不傳遞任何參數的函數,而它同時需要 res 和 req 。

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板