本文介绍了不引人注目的中间件,用于Expres.js检查请求正文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否存在第三方中间件或用于Express.js的此类中间件的创建方法,该中间件允许拦截所有请求并检查请求的正文内容,而不会影响随后的中间件,例如 bodyParser 或路由可能依赖原始主体的端点,例如 express-http-proxy ?

Does there exist a thirdparty middleware or a way to create such middleware for Express.js that allows for intercepting all requests and inspecting the request's body content without affecting subsequent middleware such as bodyParser or route endpoints which may rely on the raw body such as express-http-proxy?

据我所知,bodyParser本身似乎有点引人注目,不允许路由覆盖默认的解析行为.该快速文档描述了如何通过诸如bodyParser之类的中间件填充 request.body .从简单性和性能的角度来看,bodyParser的这种行为是有意义的,但是对于创建需要检查请求内容并使应用程序其余部分无需修改即可工作的中间件而言,它并不是一个很好的选择.鉴于解析中间件的结果可能采用完全不同的格式,因此这尤其正确.经过一番挖掘之后,我想知道是否通常可以通过express实现此功能,或者一旦阅读请求主体,就消除了使用进一步的中间件(如bodyParser或express-http-proxy)的能力,这些中间件希望访问该中间件.身体.

From what I can tell bodyParser itself seems to work in a somewhat obtrusive way that does not allow a route to override the default parsing behavior. The express documentation describes how request.body is filled in by middleware such as bodyParser. This behavior of bodyParser makes sense from simplicity and performance perspective but doesn't make it a great candidate for creating middleware which needs to inspect the contents of a request and let the remaining portion of the app working without modification. This is especially true seeing that depending on the parsing middleware the results may be in entirely different formats. After some digging I'm left wondering if it's generally possible to pull this off with express or perhaps once you read the request body you eliminate the ability to make use of further middleware such as bodyParser or express-http-proxy which expect to access the body directly.

可能相关:

推荐答案

您始终可以使用原始-body 包,带有如下所示的中间件:

You could always use the raw-body package with express middleware like so:

var getRawBody = require('raw-body');
var typer = require('media-typer');

app.use(function (req, res, next) {
  getRawBody(req, {
    length: req.headers['content-length'],
    limit: '1mb',
    encoding: typer.parse(req.headers['content-type']).parameters.charset
  }, function (err, string) {
    if (err) return next(err)
    req.text = string
    next()
  })
})

如果您唯一关心的是性能,那么我就不用太担心人体分析器,因为它不太可能对性能产生重大影响.如果可以,我建议您只将body-parser与典型的快速中间件 app.use(..)一起使用以检查请求正文.

If your only concern is performance, I wouldn't worry too much about body-parser as it's unlikely to have a massive performance impact. If you can, I'd suggest you just use body-parser with a typical express middleware app.use(..) to inspect the request body.

这篇关于不引人注目的中间件,用于Expres.js检查请求正文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-23 22:07