简体   繁体   English

在接收和解析请求主体之前,如何检查POST请求标头?

[英]How to check POST request headers before receiving and parsing request body?

When a POST request is received, is there any way to check its headers, before receiving the request body and parsing it? 收到POST请求后,在接收请求主体并对其进行解析之前,是否有任何方法可以检查其标头?

Imagine you have very large incoming POST requests (~25MB) and you need to decide whether to process them or discard them based on their headers' content. 想象一下,您有非常大的传入POST请求(〜25MB),您需要根据其标头的内容来决定是处理还是丢弃它们。

To spare bandwith, memory, cpu, and time it would be much better if it could be possible to have this flow: 为了节省带宽,内存,cpu和时间,如果可能有以下流程,那就更好了:

  1. The POST request hits the server. POST请求命中服务器。
  2. The server only receives it up to the headers content, and then holds the transmission on standby. 服务器仅接收直到标头内容的内容,然后将传输保持待机状态。
  3. The server checks the headers and decides what to do. 服务器检查标头并决定要做什么。
  4. If the headers are ok it proceeds receiving the request and parses the body, otherwise it closes the connection and sends a 401 reply. 如果标题正确,它将继续接收请求并解析正文,否则它将关闭连接并发送401答复。

Is this possible at all? 这有可能吗? If so, what is a good way to do it in Koa ? 如果是这样,在Koa中有什么好的方法?

Thanks! 谢谢!

You can't check the headers before "receiving" the body. 您不能在“接收”正文之前检查标题。 If you wanted to do something like that, you'd need create a custom function that reads bytes from a socket, and parses only the headers, and closes the connection in case of certain logic, which is probably more work than you're willing to do. 如果您想执行类似的操作,则需要创建一个自定义函数,该函数从套接字读取字节,然后仅解析标头,并在某些逻辑情况下关闭连接,这可能比您愿意做的工作还要多。去做。

What you CAN do, is create a middleware function that reads the headers and then either a) continues on to the next middleware or b) ends the request. 您可以做的是创建一个中间件功能,该功能读取标头,然后a)继续到下一个中​​间件,或者b)结束请求。 You can then make it so that this middleware is executed BEFORE the body parsing middleware (if you're using something like koa-body). 然后,您可以使其在主体解析中间件之前执行该中间件(如果您使用的是类似koa-body的东西)。 This way, although the body is already "received", the request is sent before the body is even parsed. 这样,尽管主体已经被“接收”,但请求甚至在主体被解析之前就已发送。

It's pretty easy to implement something like this, and there are plenty of guides outlining the process for creating and registering new middleware. 实现这样的东西非常容易,并且有很多指南概述了创建和注册新中间件的过程。 If you do not already know how to do it, I suggest starting here . 如果您尚不知道该怎么做,建议从这里开始。

EDIT: If you're doing file uploads and you're using multipart then it should be not a problem to check the headers using a middleware function and send a 401. That will terminate the connection and the file upload, as long as you do it before you start parsing the upload. 编辑:如果您正在执行文件上传,并且您正在使用多部分,那么使用中间件功能检查标题并发送401应该不是问题。只要您执行此操作,就会终止连接和文件上传开始解析上传文件之前。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM