1. DB 설치
저는 PostgreSQL 로 연결하려고 합니다.
PostgreSQL 을 설치하고
host: localhost
port: 5432
database: test
user: test
password:
정보를 알아둡니다.
2. 모듈 설치
연결하기 위해 모듈을 설치합니다.
npm i pg
위의 db 정보를 입력하고
테스트 쿼리를 날려보는 예제입니다.
const express = require("express");
const app = express();
const { Pool } = require("pg");
const port = 3000;
app.use(express.json());
const pool = new Pool({
user: "test",
host: "localhost",
database: "test_db",
password: "test",
port: "5432",
});
app.get("/", (req, res) => {
res.send("Hello, Node.js Backend!");
});
app.get("/data", async (req, res) => {
try {
const query = `SELECT * FROM test_schema.user;`;
const result = await pool.query(query);
res.json(result.rows);
} catch (error) {
console.error("DB error:", error);
res.status(500).send("Database error");
}
});
app.listen(port, () => {
console.log(`Server is running at http://localhost:${port}`);
});'Express' 카테고리의 다른 글
| [Express] Express CORS (0) | 2025.05.28 |
|---|---|
| [Express] Express 시작하기 (0) | 2025.05.28 |