如何在 nodejs 中处理 xhr blob post
how to handle xhr blob post in nodejs
客户代码:
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
变量超出了服务器中设置的限制大小。您必须设置一个始终大于客户端数据的数字 (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);
});
假设您的 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());
});
});
在内容过大的情况下,即使对于结构化数据,在流式传输时处理请求也是一个好主意。例如,在过去,当我使用带有大 json 请求的 body-parser#json
中间件时,我遇到了性能问题并解决了删除 body-parser#json
中间件并使用 oboe 解析流式传输的问题输入。
客户代码:
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
变量超出了服务器中设置的限制大小。您必须设置一个始终大于客户端数据的数字 (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);
});
假设您的 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());
});
});
在内容过大的情况下,即使对于结构化数据,在流式传输时处理请求也是一个好主意。例如,在过去,当我使用带有大 json 请求的 body-parser#json
中间件时,我遇到了性能问题并解决了删除 body-parser#json
中间件并使用 oboe 解析流式传输的问题输入。