Created
April 12, 2024 19:31
-
-
Save llirikkcoder/270057bfd1923ef6033c027fcdf96c53 to your computer and use it in GitHub Desktop.
postgres4you
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require('dotenv').config() | |
const express = require('express'); | |
const cors = require('cors'); | |
const bodyParser = require('body-parser'); | |
const {routes } = require('./routes/routes'); | |
const {adminRoutes} = require("./routes/adminRoutes") | |
const cookieParser = require('cookie-parser'); | |
const { Pool } = require('pg'); | |
const app = express(); | |
const fs = require('fs'); | |
const pool = new Pool({ | |
connectionString: 'postgresql://postgres:postgres4you@db:5432/postgres', | |
}); | |
app.use(express.urlencoded({ extended: false })); | |
app.use(express.json()); | |
app.use(bodyParser.urlencoded({extended: false})); | |
app.use(bodyParser.json()); | |
app.use(cookieParser()); | |
app.use(cors('*')); | |
app.get("/", function (req, res) { | |
res.send('Node is running'); | |
}) | |
// Пример запроса к базе данных | |
// app.get('/api/products', async (req, res) => { | |
// try { | |
// const client = await pool.connect(); | |
// const result = await client.query('SELECT * FROM products'); | |
// const results = { 'results': (result) ? result.rows : null}; | |
// res.json(results); | |
// client.release(); | |
// } catch (err) { | |
// console.error(err); | |
// res.send("Error " + err); | |
// } | |
// }); | |
app.use('/api/user/', routes) | |
app.use('/api/admin/', adminRoutes) | |
// Функция для выполнения запроса к базе данных | |
async function fetchData() { | |
try { | |
const client = await pool.connect(); | |
const result = await client.query('SELECT * FROM products'); | |
console.log(result.rows); // Вывод результатов в консоль | |
client.release(); | |
console.log("Data fetched successfully"); | |
} catch (err) { | |
console.error("Error fetching data:", err); | |
} | |
} | |
// Выполнение функции при запуске сервера | |
(async () => { | |
try { | |
await fetchData(); | |
console.log("Data fetched successfully"); | |
} catch (err) { | |
console.error("Error fetching data:", err); | |
} | |
})(); | |
if (module === require.main) { | |
var server = app.listen(process.env.PORT || 8000, function () { | |
var port = server.address().port; | |
console.log("App listening on port %s", port); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment