code

Express에서 "다음" 매개 변수는 무엇에 사용됩니까?

starcafe 2023. 6. 22. 22:06
반응형

Express에서 "다음" 매개 변수는 무엇에 사용됩니까?

다음과 같은 간단한 코드 블록이 있다고 가정합니다.

app.get('/', function(req, res){
    res.send('Hello World');
});

에는 두 파라미터가 .req그리고.res각각 요청 및 응답 개체를 나타냅니다.

반면에, 다음과 같은 세 번째 매개 변수를 가진 다른 함수들이 있습니다.next예를 들어, 다음 코드를 살펴보겠습니다.

app.get('/users/:id?', function(req, res, next){ // Why do we need next?
    var id = req.params.id;
    if (id) {
        // do something
    } else {
        next(); // What is this doing?
    }
});

무슨 말인지 이해할 수 없습니다next()그것이 사용되는 이유 또는 이유.예에서, 가 존재하지 , id는 요?next실제로 하고 있습니까?

다음 일치하는 경로로 제어 권한을 전달합니다.예를 들어, 당신이 제공하는 예에서, 당신은 다음과 같은 경우에 데이터베이스에서 사용자를 찾을 수 있습니다.id주어졌고, 그것을 할당했습니다.req.user.

아래에는 다음과 같은 경로가 있을 수 있습니다.

app.get('/users', function(req, res) {
  // check for and maybe do something with req.user
});

//users/123을 .123그 때에/users그 결과로 무언가를 할 수 있습니다.

루트 미들웨어는 특정 URI 방식이나 경로 순서에 의존하지 않기 때문에 더 유연하고 강력한 도구라고 생각합니다.저는 다음과 같은 예를 모델링하는 경향이 있습니다.Users 모델findOne():

function loadUser(req, res, next) {
  if (req.params.userId) {
    Users.findOne({ id: req.params.userId }, function(err, user) {
      if (err) {
        next(new Error("Couldn't find user: " + err));
        return;
      }

      req.user = user;
      next();
    });
  } else {
    next();
  }
}

// ...

app.get('/user/:userId', loadUser, function(req, res) {
  // do something with req.user
});

app.get('/users/:userId?', loadUser, function(req, res) {
  // if req.user was set, it's because userId was specified (and we found the user).
});

// Pretend there's a "loadItem()" which operates similarly, but with itemId.
app.get('/item/:itemId/addTo/:userId', loadItem, loadUser, function(req, res) {
  req.user.items.append(req.item.name);
});

이렇게 흐름을 조절할 수 있다는 것은 꽤 유용합니다.관리 플래그가 있는 사용자만 특정 페이지를 사용할 수 있도록 할 수 있습니다.

/**
 * Only allows the page to be accessed if the user is an admin.
 * Requires use of `loadUser` middleware.
 */
function requireAdmin(req, res, next) {
  if (!req.user || !req.user.admin) {
    next(new Error("Permission denied."));
    return;
  }

  next();
}

app.get('/top/secret', loadUser, requireAdmin, function(req, res) {
  res.send('blahblahblah');
});

이것이 당신에게 영감을 주었기를 바랍니다!

저도 다음()을 이해하는 데 문제가 있었지만, 이것이 도움이 되었습니다.

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

app.get("/", function(httpRequest, httpResponse, next){
    httpResponse.write("Hello");
    next(); //remove this and see what happens 
});

app.get("/", function(httpRequest, httpResponse, next){
    httpResponse.write(" World !!!");
    httpResponse.end();
});

app.listen(8080);

이해하기 전에 노드의 요청-응답 주기에 대해 자세히는 모르지만 약간의 이해가 필요합니다.사용자가 특정 리소스에 대해 HTTP 요청을 하는 것으로 시작하고 사용자에게 응답을 다시 보낼 때(예: res.send('Hello World');

아주 간단한 예를 보겠습니다.

app.get('/hello', function (req, res, next) {
  res.send('USER')
})

resp.send는 주기를 종료하고 제어권을 다시 경로 미들웨어로 넘겨주기 때문에 여기서 next()는 필요하지 않습니다.

이제 다른 예를 살펴보겠습니다.

app.get('/hello', function (req, res, next) {
  res.send("Hello World !!!!");
});

app.get('/hello', function (req, res, next) {
  res.send("Hello Planet !!!!");
});

여기에는 동일한 경로에 대한 2개의 미들웨어 기능이 있습니다.하지만 항상 첫 번째 사람에게서 반응을 얻을 수 있습니다.미들웨어 스택에 먼저 마운트되고 res.send가 사이클을 종료하기 때문입니다.

하지만 우리가 항상 "Hello World!!!!" 응답을 원하지 않는다면 어떻게 될까요?어떤 상황에서는 "Hello Planet!!!"을 원할 수도 있습니다.반응위의 코드를 수정하여 어떻게 되는지 살펴보겠습니다.

app.get('/hello', function (req, res, next) {
  if(some condition){
    next();
    return;
  }
  res.send("Hello World !!!!");  
});

app.get('/hello', function (req, res, next) {
  res.send("Hello Planet !!!!");
});

무슨 일입니까?next 이 있을 .그리고 네, 추측이 있을 수도 있습니다.조건이 참이면 첫 번째 미들웨어 함수를 건너뛰고 다음 미들웨어 함수를 호출하면 다음 미들웨어 함수가 실행됩니다."Hello Planet !!!!"대답.

다음으로 미들웨어 스택의 다음 기능으로 컨트롤을 전달합니다.

첫 번째 미들웨어 함수가 응답을 반환하지 않고 논리를 실행하면 두 번째 미들웨어 함수에서 응답을 반환받을 수 있습니다.

아래와 같은 것:-

app.get('/hello', function (req, res, next) {
  // Your piece of logic
  next();
});

app.get('/hello', function (req, res, next) {
  res.send("Hello !!!!");
});

이 경우 미들웨어 기능을 모두 호출해야 합니다.따라서 두 번째 미들웨어 기능에 도달하는 유일한 방법은 next()를 호출하는 것입니다.

다음으로 전화를 걸지 않으면 어떻게 합니까?두 번째 미들웨어 기능이 자동으로 호출될 것으로 예상하지 마십시오.첫 번째 함수를 호출한 후에는 요청이 보류된 상태로 유지됩니다.두 번째 함수는 호출되지 않으며 응답을 반환하지 않습니다.

다음은 다음 미들웨어 기능에 제어 권한을 전달하는 데 사용됩니다.그렇지 않으면 요청이 보류되거나 열려 있습니다.

여기 약간의 내부자들이 있습니다.의주목은의 주된 express app handle을 보내고 입니다.request-response cycle그리고 이 주기의 종료는 다음 중 하나에 의해 수행될 수 있습니다.response methods(예: res.end.json 등).미들웨어 또는route handler이 작업 중 response methods 핸들러나합니다.request-response cycle종료되지 않습니다.근데 이게 뭐야?next호출 위치와 방법에 따라 다릅니다.

다른 미들웨어)을 관리하려면 과 같이 하십시오.expressstacks은 그은마처럼 .queue의 시대의tasks.각각router그리고.route으로 자으로를 .stacktasks;

useexpress app 기밀task(middleware to 능에한대기▁stack의 시대의router.app.get,app.post의 etc를 .route(그 (체으로자적로자)와 stack그리고 그것을 실제로 밀어냅니다.handlers의 시대의routerouter그리고 나서 다음으로 밀어냅니다.router함수에 싸여 있습니다.route핸들러다음과 같은 경우route에 됩니다.router stack 같은 것route task (함수) subtasks밀린.

// pushes task to the router stack
app.use((req, res, next) => {
    console.log('log request');
    next();
});

// creates route, route stack, 
// pushes tasks to the route stack,
// wraps tasks in a function (another task)
// pushes wrapper function to the
// router stack
app.get('/', (req, res, next) => {
    res.send('Hello World');
});

route자기 것이 있습니다.stacknext인수 없이는 다음 핸들러만 사용할 수 있습니다.route:

app.get('/', 
    (req, res, next) => {
        console.log('first handler');
        // passes the control to the second handler
        next();
    },
    (req, res, next) => {
        console.log('second handler');
        res.send('Hello World');
    }
);

하기 르기next富士山의 middleware(express는 을 적용할 합니다.usemiddleware하면 다음으로 이동합니다.route또는middleware의 시대의router, 오류middleware 시)를 (탑재 시) 밀니다습다렸으로 밀었습니다.router stack.

next에서는 다른 인수를 사용할 수 있습니다. 모든인이 아닌 'route'또는'router'오류로 처리되고 다음으로 전달됩니다.error middleware모든 경로 뒤에 마운트되어야 하며 4개의 인수가 있어야 합니다.

// error handling middleware
app.use((error, req, res, next) => {
    res.status(error.status || 500);
    res.send(error.message || 'Server internal error');
});

'route'로서의 으로서.next 모든 파일을 건너뛸 것입니다. 건뜁다니너를 건너뜁니다.route handlers그리고 우리를 다음으로 데려갑니다.route의 시대의router:

app.get('/', 
    (req, res, next) => {
        console.log('first handler');
        // passes control to the next route
        next('route');
    },
    (req, res, next) => {
        // this handler will be skipped
        next();
    }
);

app.get('/',
    (req, res, next) => {
        // this route will be called at the end
        res.send('Hello World');
    }
);

'router'로서의 으로서.next우리를 물살에서 벗어나게 해줍니다.router:

// router 'one'
app.get('/', 
    (req, res, next) => {
        console.log('first handler');
        // passes control to the next router
        next('router');
    },
    (req, res, next) => {
        // this handler will be skipped
        next();
    }
);

// router 'two'
app.get('/',
    (req, res, next) => {
        // this route will be called at the end
        res.send('Hello World');
    }
);

나는 또한 그 이유를 덧붙이고 싶습니다.express다음 미들웨어를 호출하지 않고 제어할 수 있습니다.노드는 비동기식이므로 비동기식 호출이 완료될 때까지 기다리지 않고 다음 미들웨어를 고속으로 호출하면 응답이 불완전하거나 오류가 포함될 수 있으므로 사용자는 다음 미들웨어 함수를 호출할 시기를 제어할 수 있습니다.

언급URL : https://stackoverflow.com/questions/10695629/what-is-the-parameter-next-used-for-in-express

반응형