Programming

다음 기능을 표현합니다. 실제로 무엇을위한 것입니까?

procodes 2020. 8. 6. 20:41
반응형

다음 기능을 표현합니다. 실제로 무엇을위한 것입니까?


이 방법이하는 일에 대한 좋은 설명을 찾으려고 노력했습니다 next(). Express 문서에는 next('route')해당 경로로 건너 뛰고 사이에있는 모든 경로를 건너 뛸 수 있지만 때로는 next인수없이 호출됩니다. 아무도 next기능 을 설명하는 좋은 자습서 등을 알고 있습니까?


next()아무 논란없이 "농담, 나는 이것을 실제로 처리하고 싶지 않다"고 말합니다. 다시 들어가서 일치하는 다음 경로를 찾으려고합니다.

이것은 URL 슬러그뿐만 아니라 다른 많은 것들을 가진 일종의 페이지 관리자를 원한다면 유용합니다. 그러나 여기에 예가 있습니다.

app.get('/:pageslug', function(req, res, next){
  var page = db.findPage(req.params.pageslug);
  if (page) {
    res.send(page.body);
  } else {
    next();
  }
});

app.get('/other_routes', function() {
  //...
});

작성된 코드는 데이터베이스에 특정 ID 슬러그가있는 페이지가 있는지 확인해야합니다. 그것이 발견되면 그것을 렌더링하십시오! 하나를 찾지 못하면이 경로 처리기를 무시하고 다른 경로 처리기를 확인하십시오.

따라서 next()논증이 없으면 다른 경로 대신 다른 길을 선택할 수 있도록 경로를 처리하지 않은 척할 수 있습니다.


아니면 함께 카운터에 충돌 app.all('*'). 공유 설정 코드를 실행 한 다음 다른 경로로 이동하여보다 구체적인 작업을 수행 할 수 있습니다.

app.all('*', function(req, res, next){
  myHitCounter.count += 1;
  next();
});

app.get('/other_routes', function() {
  //...
});

대부분의 프레임 워크에서 요청을 받고 응답을 반환하려고합니다. Node.js의 비동기 특성으로 인해 사소한 일을하지 않으면 중첩 콜백에 문제가 발생합니다. 이 문제가 발생하지 않도록 Connect.js (v4.0 이전 버전의 Express.js는 connect.js 위에있는 레이어였습니다)에는 2, 3 또는 4 개의 매개 변수를 가진 함수 인 미들웨어가 있습니다.

function (<err>, req, res, next) {}

Express.js 앱은 이러한 기능의 스택입니다.

여기에 이미지 설명을 입력하십시오

라우터는 특별하며 특정 URL에 대해 하나 이상의 미들웨어를 실행할 수있는 미들웨어입니다. 스택 내부의 스택입니다.

다음은 무엇을합니까? 간단하게 앱이 다음 미들웨어를 실행하도록 지시합니다. 그러나 다음에 무언가를 전달하면 어떻게됩니까? Express는 현재 스택을 중단하고 4 개의 매개 변수가있는 모든 미들웨어를 실행합니다.

function (err, req, res, next) {}

This middleware is used to process any errors. I like to do the following:

next({ type: 'database', error: 'datacenter blew up' });

With this error I would probably tell the user something went wrong and log the real error.

function (err, req, res, next) {
   if (err.type === 'database') {
     res.send('Something went wrong user');
     console.log(err.error);
   }
};

If you picture your Express.js application as a stack you probably will be able to fix a lot of weirdness yourself. For example when you add your Cookie middleware after you router it makes sense that your routes wont have cookies.


IMHO, the accepted answer to this question is not really accurate. As others have stated, it's really about controlling when next handler in the chain is run. But I wanted to provide a little more code to make it more concrete. Say you have this simple express app:

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

app.get('/user/:id', function (req, res, next) {
    console.log('before request handler');
    next();
});

app.get('/user/:id', function (req, res, next) {
    console.log('handling request');
    res.sendStatus(200);
    next();
});

app.get('/user/:id', function (req, res, next) {
    console.log('after request handler');
    next();
});

app.listen(3000, function () {
    console.log('Example app listening on port 3000!')
});

If you do

curl http://localhost:3000/user/123

you will see this printed to console:

before request handler
handling request
after request handler

Now if you comment out the call to next() in the middle handler like this:

app.get('/user/:id', function (req, res, next) {
    console.log('handling request');
    res.sendStatus(200);
    //next();
});

You will see this on the console:

before request handler
handling request

Notice that the last handler (the one that prints after request handler) does not run. That's because you are no longer telling express to run the next handler.

So it doesn't really matter if your "main" handler (the one that returns 200) was successful or not, if you want the rest of the middlewares to run, you have to call next().

When would this come in handy? Let's say you want to log all requests that came in to some database regardless of whether or not the request succeeded.

app.get('/user/:id', function (req, res, next) {
    try {
       // ...
    }
    catch (ex) {
       // ...
    }
    finally {
       // go to the next handler regardless of what happened in this one
       next();
    }
});

app.get('/user/:id', function (req, res, next) {
    logToDatabase(req);
    next();
});

If you want the second handler to run, you have to call next() in the first handler.

Remember that node is async so it can't know when the first handler's callback has finished. You have to tell it by calling next().


next() without parameter invokes the next route handler OR next middleware in framework.


Question also asked about use of next('route') which seems to be covered week in provided answers so far:

  1. USAGE OF next():

In short: next middleware function.

Extract from this official Express JS documentation - 'writing-middleware' page:

"The middleware function myLogger simply prints a message, then passes on the request to the next middleware function in the stack by calling the next() function."

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

var myLogger = function (req, res, next) {
  console.log('LOGGED')
  next()
}

app.use(myLogger)

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

app.listen(3000)

This page of Express JS documentation states "If the current middleware function does not end the request-response cycle, it must call next() to pass control to the next middleware function. Otherwise, the request will be left hanging."

  1. USAGE OF next('route') :

In short: next route (vs. next middleware function in case of next() )

Extract from this Express JS documentation - 'using-middleware' page:

"To skip the rest of the middleware functions from a router middleware stack, call next('route') to pass control to the next route. NOTE: next('route') will work only in middleware functions that were loaded by using the app.METHOD() or router.METHOD() functions.

This example shows a middleware sub-stack that handles GET requests to the /user/:id path."

app.get('/user/:id', function (req, res, next) {
  // if the user ID is 0, skip to the next route
  if (req.params.id === '0') next('route')
  // otherwise pass the control to the next middleware function in this stack
  else next()
}, function (req, res, next) {
  // render a regular page
  res.render('regular')
})

// handler for the /user/:id path, which renders a special page
app.get('/user/:id', function (req, res, next) {
  res.render('special')
})

Its simply means pass control to the next handler.

Cheers

참고URL : https://stackoverflow.com/questions/13133071/express-next-function-what-is-it-really-for

반응형