728x90
반응형
1. mysql 연동 예제
- myapp 폴더 내에 config 폴더를 만든다.
- config폴더 내에 db.js를 만든다.
var mysql = require('mysql')
const db = mysql.createPool({
host:'localhost',
user:'root',
password:'1234',
database:'practice',
port:3306
})
module.exports=db;
- db를 연결하는 코드이다.
- module.exports=db;는 express에서 require함수를 반환받는 코드이다. (2.2에서 자세히 설명)
- mysqlWorkbench에 접속해서 practice db를 만들어주자.
- MySQL Workbench를 실행한다.
- File > new Query Tab을 클릭한다.
- 밑에 코드를 입력해 테이블을 생성하고 자료를 입력하고 권한을 설정한다.
create database practice;
use practice;
create table person(
name varchar(10),
age int,
height double
);
insert into person values('이민호', 20, 176.6);
insert into person values('송중기', 21, 172.4);
insert into person values('정채연', 22, 164.5);
select * from person;
SELECT Host, User, plugin FROM mysql.user; /*user 목록을 볼 수 있다.*/
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY '1234'; /*외부에서 Mysql db에 접속할 수 있도록 권한을 설정한다.*/
FLUSH PRIVILEGES; /*권한 설정한 것을 적용한다.*/
- Visual Studio Code로 돌아와서 server2.js 코드를 작성한다.
const express = require('express')
const app = express()
const bodyParser = require('body-parser')
const port = 3000
const db = require('./config/db.js')
app.use(bodyParser.json()) //post undefined 해결방법, jason방식으로 bodyParser 자료형을 바꾸어줘야 타입에러가 안뜬다.
app.get('/person', (req, res) => {
db.query('select * from person', (err,data)=>{ //콜백함수, err: mysql에서 오류 담는 객체, data: 구문으로 반환받은 자료 담는 객체
if(!err){
console.log(data)
res.send(data)
}else{
res.send(err)
}
})
})
//POST : http://localhost:3000/person, {"name":"신동엽","age":23,"height":176.6}
app.post('/person', (req, res)=>{
console.log('/person(post)')
console.log(req.body)
// const name = req.body.name
// const age = req.body.age
// const height = req.body.height
const {name, age, height} = req.body //비구조화할당, 구조분해 할당, destructuring assignment
db.query(`insert into person(name, age, height) values('${name}', ${age}, ${height})`,(err,data)=>{
if(!err){
console.log(data)
res.send(data)
}else{
res.send(err)
}
})
})
//PUT : http://localhost:3000/person, {"name":"송중기","age":30}
app.put('/person', (req, res)=>{
console.log('/person(put)')
const {name, age} = req.body // 비구조화 할당
db.query(`update person set age=${age} where name='${name}'`,(err,data)=>{
if(!err){
console.log(data)
res.send(data)
}else{
res.send(err)
}
})
})
//DELETE : http://localhost:3000/person, {"name":"송중기"}
app.delete('/person', (req, res)=>{
console.log('/person(delete)')
const {name} = req.body // 비구조화 할당
db.query(`delete from person where name='${name}'`,(err,data)=>{
if(!err){
console.log(data)
res.send(data)
}else{
res.send(err)
}
})
})
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`)
})
- get, post, put, delete의 간단한 예제이다.
- View단을 따로 만들지 않아 Postman로 테스트한다.
2. 더 알아가기
2.1 module.exports=db;
- module.exports = db;라는 코드는 Node.js 환경에서 사용되는 것으로, 모듈에서 특정 객체, 함수, 변수 또는 데이터를 외부로 공개(export)하는 방법을 나타냅니다. 이 코드에서 db는 데이터베이스 관련 기능이나 설정을 포함하고 있는 객체나 모듈을 가리킬 수 있습니다.
- 간단하게 설명하자면, module.exports = db; 코드는 다른 파일이나 모듈에서 이 파일을 require 함수를 사용하여 불러올 때, db 객체를 반환하도록 설정하는 것입니다. 예를 들어, 만약 이 코드가 database.js 파일 안에 있다면, 다른 파일에서 const db = require('./database.js');와 같은 방식으로 db 객체를 불러와 사용할 수 있습니다.
- req.body는 Express.js와 같은 Node.js 웹 프레임워크에서 HTTP 요청의 본문(body)을 파싱한 결과를 담고 있는 객체입니다. 웹 애플리케이션에서 클라이언트가 서버로 보낸 데이터를 쉽게 접근하고 처리할 수 있게 해 줍니다. 예를 들어, 사용자가 양식(form)을 통해 데이터를 전송할 때, 이 데이터는 req.body를 통해 사용할 수 있습니다.
2.2 bodyParser 미들웨어
- body-parser는 Express 미들웨어의 일종으로, 클라이언트로부터 오는 요청의 본문을 쉽게 추출할 수 있게 해 줍니다. 이 미들웨어는 다양한 유형의 본문 데이터를 파싱할 수 있도록 여러 파서(options)를 제공합니다:
- JSON: bodyParser.json()는 요청의 본문이 JSON 형식일 때 사용합니다. 이는 Content-Type: application/json 헤더를 가진 요청을 파싱합니다.
- URL-encoded: bodyParser.urlencoded({ extended: true })는 URL 인코딩된 데이터를 파싱하는 데 사용됩니다. 일반적으로 HTML 폼 데이터를 처리할 때 사용되며, Content-Type: application/x-www-form-urlencoded 헤더를 가진 요청을 파싱합니다.
- Raw: bodyParser.raw()는 본문을 버퍼 데이터로 처리할 때 사용됩니다.
- Text: bodyParser.text()는 텍스트 데이터를 처리할 때 사용됩니다.
- 사용 예
- 아래는 body-parser를 사용하여 JSON 및 URL-encoded 데이터를 파싱하는 예시입니다:
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
// JSON 타입의 본문을 파싱하기 위한 미들웨어
app.use(bodyParser.json());
// URL-encoded 데이터를 파싱하기 위한 미들웨어 (extended: true는 중첩된 객체를 허용함)
app.use(bodyParser.urlencoded({ extended: true }));
app.post('/profile', function(req, res) {
console.log(req.body);
res.send('Received the data!');
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
- 위 예에서 app.post('/profile', ...) 라우트 핸들러는 클라이언트가 /profile 엔드포인트로 POST 요청을 보낼 때 실행됩니다. 클라이언트가 보낸 JSON이나 URL-encoded 형식의 데이터는 bodyParser 미들웨어에 의해 파싱되어 req.body 객체로 변환되고, 이 객체에서 데이터를 읽을 수 있습니다.
- 주의
- Express 4.16.0 버전 이상에서는 body-parser의 기능이 Express에 내장되어 있어 별도로 body-parser 패키지를 설치할 필요가 없습니다. Express 내장 파서를 사용하는 방법은 다음과 같습니다:
const express = require('express');
const app = express();
// 내장된 미들웨어 사용
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
- 이렇게 내장 미들웨어를 사용하는 것이 더 간단하고 최신 방식입니다.
2.3 CMD 명령어 복습하기
npm install express
npm install mysql
- cmd창에서 해당 폴더에 express와 mysql을 사용하기 위해 설치한다.
- 새로운 디렉토리를 만들 때 마다 해줘야한다.(node_modules 파일이 생성되어 설치한다.)
node server.js
- cmd창에서 서버 실행 코드를 입력한다.
- 코드를 수정할 때 마다 프롬프트 창에서 'Ctrl+C'키를 눌러 서버 연결을 종료하고 재접속 해줘야한다.
'Coding 공부 > NodeJS_Express' 카테고리의 다른 글
[Express_Ajax_MySQL] Person 추가 연습_DB연동_JQuery_Ajax 사용 (0) | 2024.05.13 |
---|---|
[NodeJS] Node.js, Express, Express 설치 및 기본 예제, postman 간단 사용방법, Express : get, post, put, delete 예제 (1) | 2024.05.10 |
댓글