반응형
🚧 사전 작업
express 설치
npm install express --save
참고: https://expressjs.com/ko/starter/installing.html
nodemon 설치
매번 서버를 수동으로 재실행해야 하는 문제 해결
npm install nodemon --save-dev
- nodemon: 파일이 변경될 때마다 서버를 재실행해준다.
- --save-dev: 개발자 전용 라이브러리
package.json script 처리
package.json
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start":"nodemon node app.js"
},
start 부분을 입력하고 서버 실행 시에는 `npm start` 실행
body-parser 설치
로직 개선(파싱을 간단하게 할 수 있도록 도와줌)
npm install body-parser --save
- req.body를 파싱 할 수 있는 기성(ready-to-use) 미들웨어 제공
app.use(bodyParser.urlencoded({extended:false}));
- 모든 수신 요청을 파싱하고 데이터가 urlencoded 타입일 경우 본문에서 데이터를 추출한다.
- next 함수도 호출해준다. (next 함수 호출 시 앱 내의 그다음 미들웨어 함수가 호출된다.)
* 미들웨어??
Express 앱에서 사용하기 위한 미들웨어 작성
Express 앱에서 사용하기 위한 미들웨어 작성 개요 미들웨어 함수는 요청 오브젝트(req), 응답 오브젝트 (res), 그리고 애플리케이션의 요청-응답 주기 중 그 다음의 미들웨어 함수 대한 액세스 권한
expressjs.com
🔗 테스트 코드 작성
app.js
const express = require("express");
const bodyParser = require("body-parser");
const app = express();
//응답을 보내는 대신 다른 작업을 하는 미들웨어
app.use(bodyParser.urlencoded({ extended: false }));
//POST
app.post("/transaction", (req, res, next) => {
res.send("<h1> Transaction:" + req.body.transaction + "</h1>");
});
//GET
app.get("/", (req, res, next) => {
res.send(
"<form action='/transaction' method='POST'><input type='text' name='transaction'><button type='submit'>Create transaction</button></form > "
);
});
app.listen(5000);
반응형