Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

app.use 란?? 미들웨어란?? #15

Open
xzcv1994 opened this issue Mar 5, 2019 · 0 comments
Open

app.use 란?? 미들웨어란?? #15

xzcv1994 opened this issue Mar 5, 2019 · 0 comments
Labels
Web-Node.js등등 Web을 잘하고싶어요

Comments

@xzcv1994
Copy link
Owner

xzcv1994 commented Mar 5, 2019

app.use()

app.use()는 미들웨어 기능을 마운트하거나 지정된 경로에 마운트하는 데 사용된다.
기본 경로가 일치하면 미들웨어 기능이 실행된다.
app.use() 는 Express 앱에서 미들웨어 역할
app.get(), app.post()등과 달리 요청 URL을 지정하지 않아도 app.use()를 사용할 수 있으며 해당 경우에는 URL에 상관없이 매번 실행된다.
app.use() 및 app.Method() 함수를 이용해 응용프로그램 수준의 미들웨어를 app객체의 인스턴스에 바인딩
Method = get or post

미들웨어

구조 내에서 중간 처리를 위한 함수를 말한다.(모듈은 함수들의 모임)
express 프레임워크 구조 내에서 처리 목적으로 사용한다.
요청에 대한 응답 완료전 중간중간 다양한 일을 처리가능하다.
request-response 주기로 종료된다.
먼저 로드되는 미들웨어 함수가 먼저 실행

미들웨어 함수 유형 및 사용

미들웨어가 다뤄지는 영역마다 조금씩 정의의 차이가 있다.

  1. 어플리케이션 : 어플리케이션 전체 영역에서 처리 가능하다, 앱에 대한 request가 발생할 때마다 실행된다. ex) app.use(), app.Method()
  2. 라우터 : 라우터 단위로 request가 발생하면 실행, 특정 지정 라우트가 실행되었을 때마다 실행되는 미들웨어
  3. 에러 핸들링 : 에러가 발생하면 핸들링할 때 사용하는 미들웨어
  • 에러 핸들링 미들웨어는 4개의 인수(err, req, res, next)를 가짐

  • 에러가 캐치되면
    app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
    });
    위의 미들웨어 함수가 호출된다. app.use(function())처럼 아무런 url이 지정되어있지 않으므로 지정된 url이외에는 모두 에러로 처리하겠다는 것이다.
    next(err);이 호출되며
    app.use(function(err, req, res, next) {
    // set locals, only providing error in development
    res.locals.message = err.message;
    res.locals.error = req.app.get('env') === 'development' ? err : {};

// render the error page
res.status(err.status || 500);
res.render('error');
});
가 호출된다. 에러캐치와 에러 메시지를 분석하여 렌더링 하는 함수가 나뉘어 있다.
4. 써드파티 미들웨어

[출처]https://jinbroing.tistory.com/126

@xzcv1994 xzcv1994 added the Web-Node.js등등 Web을 잘하고싶어요 label Mar 5, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Web-Node.js등등 Web을 잘하고싶어요
Projects
None yet
Development

No branches or pull requests

1 participant