【问题标题】:Sails.js :remove bodyparser middleware for a specific routeSails.js :删除特定路由的 bodyparser 中间件
【发布时间】:2017-06-30 05:02:42
【问题描述】:

有什么方法可以删除特定路由的中间件

目前所有的中间件都列在http.js文件中

[
      'startRequestTimer',
      'cookieParser',
      'session',
      'bodyParser',
      'passportInit',
      'passportSession',
      'myRequestLogger',
      'handleBodyParserError',
      'compress',
      'methodOverride',
      'poweredBy',
      'router',
      'www',
      'favicon',
      '404',
      '500'
  ]

我想删除特定路由的 bodyParser 中间件

sails.js 可以吗??

【问题讨论】:

    标签: node.js sails.js body-parser


    【解决方案1】:

    没有以声明方式执行此操作的机制,但是可以,您可以在每个路由的基础上禁用中间件。您可以通过覆盖中间件并检查自定义代码中的路由 URL 来做到这一点,类似于 using a separate body parser for XML requests 的解决方案。例如:

    // In config/http.js `middleware` property
    
    bodyParser: (function() {
      // Initialize a skipper instance with the default options.
      var skipper = require('skipper')();
      // Create and return the middleware function.
      return function(req, res, next) {
        // If we see the route we want skipped, just continue.
        if (req.url === '/dont-parse-me') {
          return next();
        }
        // Otherwise use Skipper to parse the body.
        return skipper(req, res, next);
      };
    })()
    

    这是基本的想法。它当然可以做得更优雅一些。例如,如果您有几条想要跳过的路线,您可以将列表保存在单独的文件中,然后根据该列表检查当前 URL。

    【讨论】:

    • 所以需要按数组顺序调用bodyParser中间件
    • 默认情况下它已经在里面了。如果您有一个自定义的 order 数组,那么是的,您需要确保 bodyParser 在那里才能使此解决方案起作用。
    • 所以我在这里覆盖了默认的 bodyParser 中间件,对吗??
    • 没错,尽管对于大多数路由,上面的代码仍将使用 Skipper,这是默认情况下通常发生的情况。
    猜你喜欢
    • 2016-06-01
    • 2019-08-21
    • 2021-09-17
    • 1970-01-01
    • 2015-11-13
    • 1970-01-01
    • 2022-11-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多