关于 Express API app.use 中的 path 参数用法

JerryWang_汪子熙 -
关于 Express API app.use 中的 path 参数用法

SAP UI5 Tools 的 ui5.yaml 文件:

specVersion: "2.6"
type: application
metadata:
  name: my.application
server:
  customMiddleware:
    - name: myCustomMiddleware
      mountPath: /myapp
      afterMiddleware: compression
      configuration:
        debug: true

其中 mouthPath 的值会传递给 app.use 的第一个 path 参数。

path 可以指定一个具体的路径,比如下列代码,匹配路径 abcd

app.use('/abcd', function (req, res, next) {
  next()
})

也可以使用正则表达式。下列路径,匹配 abcdabd

app.use('/abc?d', function (req, res, next) {
  next()
})

下列路径,匹配 abcdabbcdabbbcd 等等:

app.use('/ab+cd', function (req, res, next) {
  next()
})

下列路径匹配 adabcd

app.use('/a(bc)?d', function (req, res, next) {
  next()
})

下列路径匹配 abcxyz

app.use(/\/abc|\/xyz/, function (req, res, next) {
  next()
})

路由将匹配紧随其路径的任何路径,并带有“/”。 例如: app.use('/apple', ...) 将匹配“/apple”、“/apple/images”、“/apple/images/news”等。

由于路径默认为“/”,因此对于应用程序的每个请求,都会执行没有路径安装的中间件。
例如,这个中间件函数将为应用程序的每个请求执行:

app.use(function (req, res, next) {
  console.log('Time: %d', Date.now())
  next()
})

下面是执行的效果:

如果删除了 next 调用,其他的中间件将永远没有机会得到执行:

错误处理中间件总是需要四个参数。必须提供四个参数以将其标识为错误处理中间件函数。

即使您不需要使用下一个对象,您也必须指定它来维护签名。 否则,下一个对象将被解释为常规中间件,并且无法处理错误。 有关错误处理中间件的详细信息,

以与其他中间件函数相同的方式定义错误处理中间件函数,唯一区别就是使用四个参数而不是三个参数,特别是使用签名 (err, req, res, next)):

app.use(function (err, req, res, next) {
  console.error(err.stack)
  res.status(500).send('Something broke!')
})
List item
特别申明:本文内容来源网络,版权归原作者所有,如有侵权请立即与我们联系(cy198701067573@163.com),我们将及时处理。

Tags 标签

后端springbootnode.jsexpresslavarel

扩展阅读

加个好友,技术交流

1628738909466805.jpg