【问题标题】:Get middleware mount point from request in Express从 Express 中的请求中获取中间件挂载点
【发布时间】:2018-02-01 10:25:34
【问题描述】:

我有一个带有路由器的 Express 应用程序,这里是路由器的示例:

const router = require('express-promise-router')();

const users = require('./users');
const validate = require('./validate');

router.get('/users', users.list);
router.get('/users/:id', users.get);
// other routes here

module.exports = router;

现在我想添加一个验证每个查询的中间件,就像这样(这不是工作示例,它只是展示我想要完成的想法):

const schemas = {
    '/users': 'some validation schema',
    '/users/:id': 'another validation'
}

module.exports = (req, res, next) => {
    const url = req.originalUrl; // This is where I'm stuck.

    if (!schemas[url]) {
        // throw new error that validation failed
    }

    // validating somehow
    if (!req.validate(schemas[url])) {
        // throw new error that validation failed
    }

    return next();
}

为此,我需要获取中间件挂载文件夹(例如“/users/557”的“/users/:id”)。我尝试使用req.originalUrl,但它返回的是完整的 URL 路径而不是挂载文件夹。

我怎样才能做到这一点?如果没有办法,我该如何编写验证中间件以使其正常工作?

【问题讨论】:

    标签: javascript node.js validation express


    【解决方案1】:

    req.route中你会得到API的路径。

    Check this screenshot

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-09-15
      • 2018-07-04
      • 1970-01-01
      • 2019-06-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多