React와 Express PostSQL을 연결하여 데이터를 저장하고 조회해보자 !!!
Express와 pg 패키지 설치
npm install express pg
React 설치
npx create-react-app my-react-app

// PostgreSQL 연결 설정
const pool = new Pool({
user: 'postgres', // PostgreSQL 사용자명
host: 'localhost', // 호스트
database: 'NodeTest', // 데이터베이스 이름
password: '사용자 비밀번호', // 사용자 비밀번호
port: 5432, // PostgreSQL 포트 (기본값: 5432)
});
// cors
npm install cors
const cors = require('cors');
app.use(cors());
// 데이터 삽입 라우트 (CREATE)
app.post('/insert', async (req, res) => {
const { name } = req.body;
try {
const result = await pool.query('INSERT INTO users (name) VALUES ($1) RETURNING *', [name]);
res.json(result.rows[0]);
} catch (err) {
console.error(err);
res.status(500).send('Server Error');
}
});
// 데이터 조회 라우트 (READ)
app.get('/select', async (req, res) => {
try {
const result = await pool.query('SELECT * FROM users');
res.json(result.rows);
} catch (err) {
console.error(err);
res.status(500).send('Server Error');
}
});
// 데이터 업데이트 라우트 (UPDATE)
app.put('/update/:id', async (req, res) => {
const { id } = req.params;
const { name } = req.body;
try {
const result = await pool.query('UPDATE users SET name = $1 WHERE id = $2 RETURNING *', [name, id]);
res.json(result.rows[0]);
} catch (err) {
console.error(err);
res.status(500).send('Server Error');
}
});
// 데이터 삭제 라우트 (DELETE)
app.delete('/delete/:id', async (req, res) => {
const { id } = req.params;
try {
const result = await pool.query('DELETE FROM users WHERE id = $1 RETURNING *', [id]);
res.json(result.rows[0]);
} catch (err) {
console.error(err);
res.status(500).send('Server Error');
}
});
import React, { useState, useEffect } from 'react';
import './App.css';
function App() {
const [name, setName] = useState('');
const [users, setUsers] = useState([]);
const [editId, setEditId] = useState(null);
useEffect(() => {
fetchUsers();
}, []);
const fetchUsers = async () => {
try {
const response = await fetch('http://localhost:3060/select');
const data = await response.json();
setUsers(data);
} catch (error) {
console.error('Error:', error);
}
};
const handleSubmit = async (e) => {
e.preventDefault();
if (editId) {
await handleUpdate();
} else {
await handleInsert();
}
};
const handleInsert = async () => {
try {
const response = await fetch('http://localhost:3060/insert', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ name }),
});
const data = await response.json();
setUsers([...users, data]);
setName('');
} catch (error) {
console.error('Error:', error);
}
};
const handleUpdate = async () => {
try {
const response = await fetch(`http://localhost:3060/update/${editId}`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ name }),
});
const data = await response.json();
setUsers(users.map(user => (user.id === editId ? data : user)));
setName('');
setEditId(null);
} catch (error) {
console.error('Error:', error);
}
};
const handleDelete = async (id) => {
try {
const response = await fetch(`http://localhost:3060/delete/${id}`, {
method: 'DELETE',
});
const data = await response.json();
setUsers(users.filter(user => user.id !== id));
} catch (error) {
console.error('Error:', error);
}
};
const handleEdit = (user) => {
setName(user.name);
setEditId(user.id);
};
return (
<div className="App">
<header className="App-header">
<form onSubmit={handleSubmit}>
<input
type="text"
placeholder="Enter your name"
value={name}
onChange={(e) => setName(e.target.value)}
/>
<button type="submit">{editId ? 'Update' : 'Submit'}</button>
</form>
<ul>
{users.map(user => (
<li key={user.id}>
{user.name}
<button onClick={() => handleEdit(user)}>Edit</button>
<button onClick={() => handleDelete(user.id)}>Delete</button>
</li>
))}
</ul>
</header>
</div>
);
}
export default App;

오늘은 3가지를 연결하여 기초적인 연습을 해봤다. 앞으로는 Mock server를 만들더라도 Dummy Data를 만들지 않고 직접 데이터베이스를 연결하여 사용해 봐야겠다. 오늘도 성장한 기분 럭키비키잖아~~!!🍀!!🍀