美文网首页
express的next()函数

express的next()函数

作者: CodingCode | 来源:发表于2020-07-19 11:49 被阅读0次

express的next()函数

在定义middleware和route的时候我们经常看到next函数,表示跳转到下一个middle或者route函数,这是最常见的用法,其next()是不带参数的;其实next()函数还可以带参数,总结如下:

  1. next() 不带参数
    表示继续跳转执行下一个middle或者route函数。
  2. next('route')
    表示丢弃当前route的剩余callback函数,注意只在由app.METHOD()/route.METHOD()中定义的middleware函数中生效。
  3. next(! 'route')
    对于任何非'route'参数(不管是一个简单数字或者还是一个字符串)都被认为是一个err,跳转到错误处理函数。

这儿我们举几个例子说明next('route')的用法。

app.get('/hello', (req, res, next) => {
  console.log('in get 1');
  next()
}, (req, res, next) => {
  console.log('in get 2');
  next()
}, (req, res, next) => {
  console.log('in get 3');
  next()
});

app.get('/hello', (req, res, next) => {
  console.log('in get 4');
});

在这个例子中四个callback都会被调用到。
我们改一下在第二个callback中使用next('route')

app.get('/hello', (req, res, next) => {
  console.log('in get 1');
  next()
}, (req, res, next) => {
  console.log('in get 2');
  next('route')  // this will skip the next callback
}, (req, res, next) => {
  console.log('in get 3');
  next()
});

app.get('/hello', (req, res, next) => {
  console.log('in get 4');
});

运行结果呢:

in get 1
in get 2
in get 4

可见第三个callback函数被skip掉了。

如果我们定义router.get()函数也是这个结果:

const express = require('express');
const app = express();
const router = express.Router()

router.get('/hello', (req, res, next) => {
  console.log('in get 1');
  next()
}, (req, res, next) => {
  console.log('in get 2');
  next()
}, (req, res, next) => {
  console.log('in get 3');
  next()
});

router.get('/hello', (req, res, next) => {
  console.log('in get 4');
});

app.use('/', router);

此时四个callback都能被回调。

const express = require('express');
const app = express();
const router = express.Router()

router.get('/hello', (req, res, next) => {
  console.log('in get 1');
  next()
}, (req, res, next) => {
  console.log('in get 2');
  next('route')  // this will skip the next callback
}, (req, res, next) => {
  console.log('in get 3');
  next()
});

router.get('/hello', (req, res, next) => {
  console.log('in get 4');
});

app.use('/', router);

此时只有三个callback能够被回调,即:

in get 1
in get 2
in get 4

相关文章

网友评论

      本文标题:express的next()函数

      本文链接:https://www.haomeiwen.com/subject/oqulkktx.html