forked from Eugeniu90/nodejs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
54 lines (45 loc) · 1.49 KB
/
app.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const { Client } = require('pg');
const dbConfig = {
user: 'postgres', // Replace with your database username
host: 'default-poc-1.c8or4ndxnhjc.eu-west-1.rds.amazonaws.com', // Replace with your RDS endpoint
database: 'postgres', // Replace with your database name
password: 'lZS6clY{1p.8', // Replace with your database password
port: 5432 // Replace with your database port
};
const client = new Client(dbConfig);
client.connect(err => {
if (err) {
console.error('Connection error', err.stack);
} else {
console.log('Connected to database');
}
});
// Body parser middleware
app.use(bodyParser.json());
// GET /status
app.get('/status', (req, res) => {
res.json({ status: 'Application is running' });
});
// POST /data
app.post('/data', async (req, res) => {
const data = req.body;
try {
const result = await client.query('INSERT INTO postgres (data) VALUES ($1) RETURNING *', [data]);
console.log('Data inserted:', result.rows[0]);
res.json({ status: 'Data received and stored in PostgreSQL', insertedData: result.rows[0] });
} catch (error) {
console.error('Error inserting data:', error);
res.status(500).json({ error: 'Internal Server Error' });
}
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
process.on('SIGINT', () => {
client.end();
process.exit();
});