express
express
란 Node.js를 위한 빠르고 자유로운 미니멀리즘 웹 프레임워크라고 합니다?, http 유틸리티 메소드 및 미들웨어 작성으로 API(Appliction Programming Interface)를 작성할 수 있습니다.
express 시작하기
## bash
# project 폴더 생성
mkdir test && cd test
# package.json 생성
npm init
# express를 사용하기 위해서 설치
npm install express
먼저, 시작하는 방법은 npm으로 시작할 시에는 위와 같이 시작하면 됩니다.
기본 미들웨어 작성
import express from "express"
const port = 8080; // 포트 번호 설정
const app = express(); // express 객체 생성
/**
* http method, get
* http path, /
* http 미들웨어 function request, response 호출
* next 생략
*/
app.get("/", function(request, response/*, next*/) {
response.send("hellow world"); // 응답
});
app.listen(port);
http 메소드 get, 경로 "/"을 받으면 "hellow word"를 응답합니다.
콜벡, next 이용
import express from "express"
const port = 8080; // 포트 번호 설정
const app = express(); // express 객체 생성
/**
* 요청 req
* 응답 res
* 미들웨어 함수에 대한 콜백 next
*/
var nextMiddle = function (req, res, next) {
console.log("step1"); // step1 출력
next(); // next함수 호출
}; // 미들웨어 함수 작섬
app.use(nextMiddle); // nextMiddle 사용 선언
/**
* http method get 요청
* 미들웨어 함수, request, respons -> req, res 호출
*/
app.get('/', function(req, res) {
console.log("step2"); // step 출력
res.send('Hello World!'); // 응답
});
app.listen(port);
callback인 next()를 사용해서 step1, step2를 차례대로 사용한 것을 알 수 있습니다.
next 콜백, 데이터 전달
import express from "express"
const port = 8080; // 포트 번호 설정
const app = express(); // express 객체 생성
/**
* 요청 req
* 응답 res
* 미들웨어 함수에 대한 콜백 next
*/
var nextMiddle = function (req, res, next) {
req.test = "전달"
next(); // next함수 호출
}; // 미들웨어 함수 작성
app.use(nextMiddle); // nextMiddle 사용 선언
/**
* http method get 요청
* 미들웨어 함수, request, respons -> req, res 호출
*/
app.get('/', function(req, res) {
console.log(req.test); // step 출력
res.send('Hello World!'); // 응답
});
app.listen(port);
미들웨어 함수를 지정하여 app.use(nextMiddle)을 호출했습니다. 그리고 다음 req(요청 오브젝트)를 추가하여 전달합니다.
'프로잭트' 카테고리의 다른 글
BEB 블록체인 2기 후기 (0) | 2022.04.09 |
---|