프로그래밍
[node.js]DB테이블 구축 및 Express와 연동하기
재은이
2021. 12. 23. 15:17
728x90
반응형
USE management;
CREATE TABLE CUSTOMER (
id INT AUTO_INCREMENT PRIMARY KEY,
image VARCHAR(1024),
name VARCHAR(64),
birthday VARCHAR(64),
gender VARCHAR(64),
job VARCHAR(64)
)DEFAULT CHARACTER SET UTF8 COLLATE utf8_general_ci;
SELECT * FROM CUSTOMER;
INSERT INTO CUSTOMER VALUES (1,'https://placeimg.com/64/64/1', '김재은','970220','여자','취준생');
INSERT INTO CUSTOMER VALUES (2,'https://placeimg.com/64/64/2', '김재영','980901','여자','동생');
INSERT INTO CUSTOMER VALUES (3,'https://placeimg.com/64/64/3', '김영호','630912','남자','아빠');
mysql을 설치해서 테이블을 생성하였다.
db연동(서버에서 해당데이터베이스에 접근해서 데이터 얻어오기)
database.json파일 만들어서 gitignore처리 해주기(내 소중한 계정정보 github올라가면 안돼서)
그럼 database.json파일이름이 회색으로 변함
터미널에서 C:\React Project Turorial\management>npm install --save mysql 입력하여 mysql설치
server.js 수정
const fs = require('fs');
const data = fs.readFileSync('./database.json');//동기식으로 관리할 데이터베이스 json 파일 경로 설정
const conf = JSON.parse(data); //해당 환경설정 데이터 파싱해서 가져오기
const mysql = require('mysql');//oracle라이브러리 불러오기
const connection = mysql.createConnection({
host : conf.host,
user : conf.user,
password : conf.password,
port : conf.port,
database : conf.database
});
connection.connect();
//client가 /api/customers에 접속을 하게되면 client에게 데이터를 반환할 수 있도록 하기
///api/customers에 접속하면 json 형태로 데이터 반환
app.get('/api/customers',(req,res) =>{
connection.query(
"SELECT * FROM CUSTOMER",
(err,rows,fields) =>{
res.send(rows);
}
);
});
app.listen(port, () => console.log(`Listening on port ${port}`));
다시 얀데브 해보면
이쁘게 잘뜬다
서버와 통신하는걸 확인하기 위해 네트워크창 확인해보면 customers api에 접근해서 데이터 잘 받아오고있다.
Create Customer Database Table & Node.js Database Connection Settings · kimjaeeungit/React-Management-Tutorial@dfb56d9
Permalink This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository. Browse files Create Customer Database Table & Node.js Database Connection Settings Loading branch information Showing 4 changed file
github.com
728x90
반응형