如何在Node.js中处理XHR Blob POST请求

4

客户端代码:

var xhr = new XMLHttpRequest();
xhr.open('POST', '/frame', true);
xhr.send(blob);

服务器代码:

app.use(bodyParser.urlencoded({extended: false,limit: '50mb'}));
app.post('/frame', function (req, resp) {
    console.log(req.body);
});

这会导致 PayloadTooLargeError 错误:参数过多。添加的内容是:
xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded');

解决问题的方法不止这一种。还有其他想法吗?

你能提供“blob”的内容吗? - leobelizquierdo
2个回答

8
假设您的blob变量不是真正的url编码表单数据,而只是任何一种内容。那么在服务器端,您可以直接读取请求流。请记住,在http.Server.request事件处理程序中,req变量是一个可读流。这将消除body-parser中间件所施加的任何大小限制。保持您原始的客户端代码,则您的服务器代码应该如下:
// app.use(bodyParser.urlencoded({extended: false,limit: '50mb'}));

app.post('/frame', function (req, resp) {
  req.on('readable', function(){
    console.log(req.read());
  });
});

即使处理的数据是结构化的,如果内容过大,按流式传输处理请求也是一个好主意。例如,我曾经在使用body-parser#json中间件处理大型JSON请求时遇到了性能问题,并通过移除body-parser#json中间件并使用oboe来解析流输入来解决了这个问题。


你能提供几个相关的参考文献吗? - Richie
1
传递给request事件处理程序的req参数是https://nodejs.org/api/http.html#http_class_http_incomingmessage类的实例。根据文档,该类是一个可读流。有了这些信息,您可以搜索节点流文档,并使用可读流API,就像示例代码中注册readable事件处理程序一样。 - yeiniel

2

您的 blob 变量超过了服务器设置的限制大小。您必须设置一个始终大于客户端数据(blob)的数字。

客户端:

var xhr = new XMLHttpRequest();
xhr.open('POST', '/frame', true);
xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded');
xhr.send(blob);

服务器:

// set limit with a value always bigger than the client data
var upperBound = '1gb';
app.use(bodyParser.urlencoded({extended: false, limit: upperBound}));
app.post('/frame', function (req, resp) {
    console.log(req.body);
});

记得设置 content-type 并调用适当的 bodyParser.method()。例如,如果 blob 包含图像,则 content-type 应为 application/octet-stream,需要调用的 bodyParser 方法是 raw()。否则服务器将抛出错误。 - Menixator

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接