middleware

혜인·2022년 4월 1일
0

미들웨어 middleware

클라이언트와 서버를 연결하여 데이터를 주고받을 수 있도록 중간에서 매개 역할을 하는 SW

미들웨어는 함수다.
운영체제가 주는 영역 밖에서 영향을 주는 일반적인 서비스들과 가용성있는 프로그램들
주로 Datamanagement, Application service, Messaging, Authenication, API management 들을 관리한다.
request받고 response내뱉고 next있으면 거기로 보내는 것

종류

  • 어플리케이션 수준 Application-level
  • 라우터 수준 Router-level
  • 오류 처리 Error-handling
  • 내장 Built-in
  • 타사 Third-party

예시

const express = require('express');
const app = express();

express프레임워크를 가져와서 사용한다고 선언한다.

app.use(login)

미들웨어를 사용하려면 use를 써야 한다.
맨 위에 미들웨어를 실행하겠다 라는 것은 전역에서 미들웨어를 사용하겠다는 뜻

app.get('/',(req,res, next) => {
	console.log("homepage")
	res.send("<h1>HOMEPAGE</h1>"
});
app.get('/user',auth,(req,res, next) => {
	console.log("userpage")
	res.send("<h1>USER</h1>"
});
function login(req,res,next) {
	console.log("login.....")
    next();
}

next는 다음 미들웨어를 찾아서 실행한다는 함수

function auth(req,res,next){
	console.log("authentication...")
    
    if(req.query.admin === "true" ) {
    	req.admin = true;
        
        next();
    }else {
    	res.send("<h1>No athenticated!</h1>");
    }
}
app.listen(100)

next()가 미들웨어 내에 없다면 ?

다음이 실행이 안됨
오류가 나면 가지말고, 오류가 안났으면 가라고 할 수 있다.

0개의 댓글