목차
Express란?
NodeJS를 사용하여 쉽게 웹 서버를 생성하는 것과 관련된 기능을 담당하는 프레임워크
- 웹 애플리케이션을 만들기 위한 각종 메소드와 미들웨어 등이 내장되어 있다.
- 라우팅, 인증, 데이터베이스 연결, 에러 처리 등 다양한 기능을 제공한다.
Express 설치
npm install express
Express 사용
app.js
const express = require('express');
// Node.js의 CommonJS 모듈 시스템을 사용하여 'express' 모듈을 가져옴
const app = express();
// express() 함수를 호출하여 새로운 Express 애플리케이션 객체 app을 만듦
const PORT = 8000;
// 서버가 사용할 포트 번호를 8000으로 설정
app.get('/', function (req, res) {
// '/' 경로로 들어오는 GET 요청을 처리
res.send('hello express');
// 응답 객체의 send 메서드를 사용하여 클라이언트로 'hello express' 문자열을 보냄
});
app.listen(PORT, function () {
// 서버를 시작하고 포트 8000에서 수신 대기하도록 설정
console.log(`Listening on port ${PORT}! http://localhost:${PORT}`);
});
서버 실행
node app.js
Express 미들웨어
미들웨어란?
- 요청이 들어옴에 따라 응답까지의 중간 과정을 함수로 분리한 것
- 서버와 클라이언트를 이어주는 중간 작업
- use() 를 이용해 등록할 수 있다.
쉽게 말해 클라이언트와 서버 사이에서 통역사 역할을 해준다고 보면 된다.
자주 쓰는 내장 미들웨어
클라이언트로부터 오는 요청 데이터를 서버에서 사용할 수 있는 형식으로 파싱하는 역할
app.use(express.urlencoded({ extended: true })); // URL 인코딩된 데이터 파싱
app.use(express.json()); // JSON 데이터 파싱
정적 파일을 제공하기 위해 사용
app.use('/public', express.static(__dirname + '/static'));
// /public 경로로 들어오는 요청을 현재 파일의 디렉토리에 위치한 'static' 디렉토리 안의 정적 파일로 제공하도록 설정합니다.
// 이렇게 함으로써 예를 들어 이미지 파일이나 다른 정적 파일들을 웹 브라우저에서 직접 접근할 수 있게 됩니다.
클라이언트와 서버 데이터 전송 방법
form 태그 이용 방법
GET 방식
views/index.html
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>폼 전송</title>
</head>
<body>
<h1>GET 방식</h1>
<form action="/getForm" method="get">
<div>
<input type="text" name="id" placeholder="ID" required />
</div>
<div>
<input type="password" name="pw" placeholder="PW" required />
</div>
<div>
<button type="submit">제출</button>
</div>
</form>
</body>
</html>
app.js
const express = require('express');
const app = express();
const PORT = 3000;
const path = require('path');
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.get('/', function (req, res) {
res.sendFile(path.join(__dirname + '/views/index.html'));
});
// GET 방식은 클라이언트에서 보낸 데이터가 req.query에 저장
app.get('/getForm', (req, res) => {
console.log(req.query);
res.send(req.query);
});
app.listen(PORT, () => {
console.log('연결 성공');
});
POST 방식
views/index.html
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>폼 전송</title>
</head>
<body>
<h1>POST 방식</h1>
<form action="/postForm" method="post">
<div>
<input type="text" name="id" placeholder="ID" required />
</div>
<div>
<input type="password" name="pw" placeholder="PW" required />
</div>
<div>
<button type="submit">제출</button>
</div>
</form>
</body>
</html>
app.js
const express = require('express');
const app = express();
const PORT = 3000;
const path = require('path');
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.get('/', function (req, res) {
res.sendFile(path.join(__dirname + '/views/index.html'));
});
// POST 방식은 클라이언트에서 보낸 데이터가 req.body에 저장
app.post('/postForm', (req, res) => {
console.log(req.body);
res.send(req.body);
});
app.listen(PORT, () => {
console.log('연결 성공');
});
fetch API 이용 방법
GET 방식
views/index.html
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>폼 전송</title>
</head>
<body>
<h1>GET 방식</h1>
<form class="form">
<div>
<input type="text" name="id" placeholder="ID" required />
</div>
<div>
<input type="password" name="pw" placeholder="PW" required />
</div>
<div>
<button type="submit" class="btn">제출</button>
</div>
</form>
<script>
const btn = document.querySelector('.btn');
btn.addEventListener('click', (e) => {
e.preventDefault();
const form = document.querySelector('.form');
const id = form.id.value;
const pw = form.pw.value;
const query = `?id=${id}&pw=${pw}`;
fetch(`/getFetch${query}`).then((response) => {
return response.json();
}).then((data) => {
console.log(data);
})
})
</script>
</body>
</html>
app.js
const express = require('express');
const app = express();
const PORT = 3000;
const path = require('path');
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.get('/', function (req, res) {
res.sendFile(path.join(__dirname + '/views/index.html'));
});
// GET 방식은 클라이언트에서 보낸 데이터가 req.query에 저장
app.get('/getFetch', (req, res) => {
console.log(req.query);
res.send(req.query);
});
app.listen(PORT, () => {
console.log('연결 성공');
});
POST 방식
views/index.html
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>폼 전송</title>
</head>
<body>
<h1>POST 방식</h1>
<form class="form">
<div>
<input type="text" name="id" placeholder="ID" required />
</div>
<div>
<input type="password" name="pw" placeholder="PW" required />
</div>
<div>
<button type="submit" class="btn">제출</button>
</div>
</form>
<script>
const btn = document.querySelector('.btn');
btn.addEventListener('click', (e) => {
e.preventDefault();
const form = document.querySelector('.form');
const id = form.id.value;
const pw = form.pw.value;
const data = {
id,
pw,
};
fetch(`/postFetch`, {
method: 'post',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data)
}).then((response) => {
return response.json();
}).then((data) => {
console.log(data);
})
})
</script>
</body>
</html>
app.js
const express = require('express');
const app = express();
const PORT = 3000;
const path = require('path');
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.get('/', function (req, res) {
res.sendFile(path.join(__dirname + '/views/index.html'));
});
// post 방식은 클라이언트에서 보낸 데이터가 req.body에 저장
app.post('/postFetch', (req, res) => {
console.log(req.body);
res.send(req.body);
});
app.listen(PORT, () => {
console.log('연결 성공');
});
결과 화면
반응형