Notice
Recent Posts
Recent Comments
Link
HANA -J
TIL - node.js 미들웨어 본문
- 미들웨어란 ?
클라이언트에서 요청이 오고 그요청을 서버에 보내기 위해 중간에서 목적에 맞게 매개역할을 하는 소프트웨어.
=>Express 애플리케이션은 본질적으로 일련의 미들웨어 함수의 호출이다.
//Application level
//use, method(get,post, put, delete 등) 메서드로 미들웨어를 만든다.
app.use(function(req, res, next) { //어떤 경로로 들어와도 동작하겟다!
console.log('여기는 실행');
next() //다음미들웨어가 동작하도록 하는 callback함수
})
app.get('/user/:id', function (req, res,next){ //해당 경로에서만 미들웨어가 동작하도록 지정할 수 있다.
res.send('id 받음');
});
//Router level
var express = require('express');
var app = express();
var router = express.Router(); //Router() 인스턴스에 바인딩 된다는 점을 제외하면 어플리케이션 미들웨어와 동일하게 동작
router.use(function (req, res, next) {
console.log('here');
next();
});
router.get('/user/:id', function(req, res, next) {
console.log(req.params)
res.status(200);
});
//Error handling
app.use(function(err, req, res, next) { //오류처리 미들웨어는 항상 4개의 인수 사용
console.log(err.stack);
res.status(500).send('Error!!!');
});
//Built-in
//express가 내장한 미들웨어들을 의미
express.json()
express.raw()
express.Router()
express.urlencoded()
//Third-party
const bodyParser = require(’body-parser”)
app.use(bodyParser.json());
app.use(bodyParser.urlendcoded({extended:false}));
//=> 위의 코드를 작성해면 아래처럼 사용이 가능
app.post("/login", (req, res)=>{
console.log(req.body);
}); //{id :"hana", password:"1234"}
//미들웨어를 등록하지 않으면 body라는 프로퍼티가 req내에 없으므로 "undefined"가 출력된다.
728x90
'what I Learnd > TIL' 카테고리의 다른 글
데이터 분석 (0) | 2023.07.04 |
---|---|
클래스 101 : 팔리는 글쓰기 (1) (0) | 2022.09.15 |
TIL - node.js require, import (0) | 2022.02.16 |
TIL - OSI 7 계층, TCP/IP 4 계층 (0) | 2022.02.09 |
TIL - Nest.js (0) | 2022.02.08 |
Comments