더이상 하지 않는 Backend - NodeJS/Node-Express 개론(완)
Express - 1장 : 설치부터 요청처리와 REST API 개념정리
VictorMeredith
2023. 2. 26. 21:52
설치/세팅
// 1. 빈폴더에
npm init -y -> entry point : server.js 로 세팅
// 2. express 설치
npm i express
// 3. (server.js 파일)
const express = require('express'); // CJS module 방식
const app = express();
app.listen(8080, function() {
console.log('listening on 8080')
})
// 4. nodemon 세팅
npm i -g nodemon
// 5. 실행 :
nodemon server.js
GET요청 처리
// 1. send 처리
app.get('/주소', (req, res) => {
res.send('message') //send 처리
})
// 2. sendFile처리
app.get('/', (req, 응답) => {
res.sendFile(__dirname +'/index.html') //send file 처리
}); //__dirname은 현재 파일의 경로
POST요청 처리
// 1. body-parser 세팅
// 1)설치
npm i body-parser
// 2) server.js
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({extended : true}));
app.use(bodyParser.json());
// 2. POST요청할 예시(form tag) (/add 로 요청)
<form action="/add" method="POST">
// 3. POST 요청 처리
app.post('/add', (req, res) => {
res.send('전송완료')
});
REST API란
REST API란 ? Representational State Transfer
API : Application Programming Interface ;
REST논문에서 나온 서버원칙 규약
REST원칙 :
1. Uniform Interface :
- 하나의 자료는 하나의 URL로
- 요청과 응답은 정보가 충분히 들어가야함
2. Client-Server 역할 구분 명확히
- 브라우저는 요청만 할 뿐 / 서버는 응답만 할 뿐
3. Stateless
- 요청1과 요청2는 의존성이 없어야함
4. Cacheable
- 요청을 통해 보내는 자료들은 캐싱이 가능해야 한다.
- 캐싱가능하다고 표시하거나 캐싱기간을 설정해주어야 한다.
- 브라우저가 해줌 캐싱
5. Layered System
- 단계를 거쳐서 요청을 처리해도 된다.
6. Code on Demand
- 서버는 고객에게 실제 실행가능한 코드를 전송해줄 수도 있다.
- 요새 서버를 잘 안해서 빠른 복습이 필요하다..