PostgreSQL
Implementation:
Step 1: Setup a server site application
Prerequisites
Install required packages
Node JS Express (express)
PostgreSQL (pg)
Cross-Origin Resource Sharing (cors)
Body Parser middleware (body-parser)
npm install express pg cors body-parser
Setup server using Express (server.js)
const express = require('express');
const { Client } = require('pg');
const cors = require('cors');
const bodyParser = require('body-parser');
const app = express();
app.use(cors());
app.use(bodyParser.json());
const port = 5000;
const client = new Client({
user: 'postgres', // username of postgreSQL database
host: 'localhost', // host of postgreSQL database
database: '', // name of the database
password: '', // password of your postgreSQL application
port: 5432, // default port 5432
});
client.connect();
//method to interact with the database
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
Set up method (interact with database)
app.get('/api/testing', async (req, res) => {
try {
const result = await client.query('SELECT * FROM testing');
res.json(result.rows);
} catch (error) {
console.error('Error fetching items:', error);
res.status(500).json({ error: 'Internal Server Error', details: error.message });
}
});
Run the express server
In terminal
node server.js
Step 2: Setup a client site application
Prerequisites
Install required packages
Axios Vue 3 (axios)
npm install axios
Example: Retrieve data and display on screen
frontend code to display received data
<el-table :data="tableData" style="width: 80%" :row-class-name="tableRowClassName">
<el-table-column prop="name" label="Name" width="180"></el-table-column>
<el-table-column prop="price" label="Price" width="180"></el-table-column>
<el-table-column prop="quantity" label="Quantity" width="180"></el-table-column>
<el-table-column label="Actions">
<template v-slot="scope">
<el-button type="danger" @click="deleteItem(scope.row.name)">Delete</el-button>
<el-button type="warning" @click="showUpdateDialog(scope.row)">Modify</el-button>
</template>
</el-table-column>
</el-table>
method to retrieve data using axios
import axios from 'axios';
export default {
data() {
return {
tableData: [],
};
},
mounted() {
this.fetchData();
},
methods: {
async fetchData() {
try {
const response = await axios.get('http://localhost:5000/api/testing');
this.tableData = response.data;
} catch (error) {
console.error('Error fetching data:', error);
}
},
},
};
Run the client site application
npm run serve
Last updated