IT

app.all ( '*')과 app.use ( '/')의 차이점

lottoking 2020. 8. 3. 17:30
반응형

app.all ( '*')과 app.use ( '/')의 차이점


Node.JS Express app.all('*', ... )유용한 차이점이 app.use('/', ...)있습니까?


대부분의 경우 동일한 방식으로 작동합니다. 가장 큰 차이점은 미들웨어가 적용되는 순서입니다.

  • app.all() 응용 프로그램의 라우터에 연결됩니다 app.router 미들웨어에 도달 할 때마다 사용 (모든 메소드 경로 ... GET, POST 등을 처리).

주의 사항 : app.router는 Express 4.x에서 더 이상 사용되지 않습니다.

  • app.use()응용 프로그램의 기본 미들웨어 스택에 연결되는 미들웨어에 지정된 순서대로 사용됩니다. 예를 들어, 먼저 먼저 실행됩니다. 마지막으로 (라우터 더 많이) 놓으면 보통 전혀 실행되지 않습니다.

일반적으로 모든 경로에 대해 많은 작업을 수행해야합니다. app.use ()가 더 나은 옵션입니다. 또한 명시 적 0.4가 암시 적 라우터를 떨어 뜨릴 가능성이 있습니다. 즉, 기술적으로는 사용할 필요가 있는지 미들웨어에서 라이브러리의 위치가 현재보다 더 중요합니다. 지금).


app.use 는 하나의 지속되는 함수 만 사용하며 미들웨어를위한 것입니다. 미들웨어는 일반적으로 요청 및 응답을 처리하지 않습니다. (기술적으로는 가능) 입력 데이터 만 처리하고 큐의 다음 처리기로 전달합니다.

app.use([path], function)

app.all 은 여러 개의 장소를 취하며 라우팅을위한 것입니다. 여러 개의 단일 서비스를 사용하면 요청을 필터링하고 응답을 보낼 수 있습니다. express.js 의 필터에 설명되어 있습니다.

app.all(path, [callback...], callback)

app.use 는 URL이 지정된 경로로 시작하는지 여부 만 확인합니다.

app.use( "/product" , mymiddleware);
// will match /product
// will match /product/cool
// will match /product/foo

app.all 은 완전한 경로와 일치합니다

app.all( "/product" , handler);
// will match /product
// won't match /product/cool   <-- important
// won't match /product/foo    <-- important

app.all( "/product/*" , handler);
// won't match /product        <-- Important
// will match /product/
// will match /product/cool
// will match /product/foo

  • app.use :

    1. 헤더, 쿠키, 세션 등을 구성하는 middlware를 프론트 컨트롤러에 삽입하십시오.
    2. app [http_method] 전에 작성해야합니다. 문서는 실행되지 않습니다.
    3. 몇 번의 통화는 순서대로 처리됩니다.
  • app.all :

    1. (app [http_method]와 같은)는 경로의 컨트롤러를 구성하는 데 사용됩니다.
    2. "all"은 모든 http 메소드에 적용됨을 의미합니다.
    3. 몇 번의 통화는 순서대로 처리됩니다.

이 expressJs 코드 샘플을.

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

app.use(function frontControllerMiddlewareExecuted(req, res, next){
  console.log('(1) this frontControllerMiddlewareExecuted is executed');
  next();
});

app.all('*', function(req, res, next){
  console.log('(2) route middleware for all method and path pattern "*", executed first and can do stuff before going next');
  next();
});

app.all('/hello', function(req, res, next){
  console.log('(3) route middleware for all method and path pattern "/hello", executed second and can do stuff before going next');
  next();
});

app.use(function frontControllerMiddlewareNotExecuted(req, res, next){
  console.log('(4) this frontControllerMiddlewareNotExecuted is not executed');
  next();
});

app.get('/hello', function(req, res){
  console.log('(5) route middleware for method GET and path patter "/hello", executed last and I do my stuff sending response');
  res.send('Hello World');
});

app.listen(80);

'/ hello'경로에 액세스 할 때의 로그는 다음과 있습니다.

(1) this frontControllerMiddlewareExecuted is executed
(2) route middleware for all method and path pattern "*", executed first and can do stuff before going next
(3) route middleware for all method and path pattern "/hello", executed second and can do stuff before going next
(5) route middleware for method GET and path patter "/hello", executed last and I do my stuff sending response

을 사용 app.use()하면 "마운트"경로가 제거되고 미들웨어 기능에 표시되지 않습니다.

app.use('/static', express.static(__dirname + '/public'));

마운트 된 미들웨어 함수 ( express.static)는 req.url에이 접두사 ( /static) 포함되어 있지 않으면 호출되지 않습니다. 이 접두어 는 함수가 호출 될 때 제거 됩니다.

를 사용하면 app.all()해당 동작이 없습니다.


예, app.all()모든 유형의 요청 방법 (POST, GET, PUT 또는 DELETE)을 사용하여 특정 URI가 요청 될 때 호출됩니다.

반면 app.use()에 모든 미들웨어에 사용되며 경로 접두사에 마운트되며 해당 경로 아래의 URI가 요청 될 때마다 호출됩니다.

다음은 app.allapp.use에 대한 설명서입니다 .


위의 모든 답변은 두 가지 차이점이 없습니다.

첫 번째 : app.all정규식을 경로 매개 변수로 허용합니다. app.use정규식을 허용하지 않습니다.

두 번째 : app.all(path,handler)또는 app[method](path,handler), 핸들러 path모든 path . 이것은, app [method] '경로가 완성되었습니다.

app.use(path,hanlder), 사용 경로가 완료되면 hanlder 경로는 '/'이어야하며 사용 경로가 전체 경로의 시작 인 경우 핸들러 경로는 나머지 전체 경로 여야합니다.

 app.use('/users', users);

  //users.js:  the handler will be called when matchs `/user/` path
      router.get('/', function(req, res, next) {
      res.send('respond with a resource');
    });
  // others.js: the handler will be called when matchs `/users/users` path
      router.get('/users', function(req, res, next) {
      res.send('respond with a resource');
    });

app.all('/users', users);

//others.js: the handler wil be called when matchs `/`path
router.get('/', function(req, res, next) {
     res.send('respond with a resource');
});
//users.js: the handler will be called when matchs `/users` path
router.get('/users', function(req, res, next) {
    res.send('respond with a resource');
 });

참고 URL : https://stackoverflow.com/questions/14125997/difference-between-app-all-and-app-use

반응형