从node.js的http.IncomingMessage获取请求正文 [英] Get request body from node.js's http.IncomingMessage

查看:992
本文介绍了从node.js的http.IncomingMessage获取请求正文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为用node.js编写的应用程序实现一个简单的HTTP端点.我已经创建了HTTP服务器,但是现在我不得不阅读请求内容正文:

I'm trying to implement a simple HTTP endpoint for an application written in node.js. I've created the HTTP server, but now I'm stuck on reading the request content body:

http.createServer(function(r, s) {
    console.log(r.method, r.url, r.headers);
    console.log(r.read());
    s.write("OK"); 
    s.end(); 
}).listen(42646);

请求的方法,URL和标头可以正确打印,但是r.read()始终为NULL.我可以说这对请求的发出方式没有问题,因为content-length标头在服务器端大于零.

Request's method, URL and headers are printed correctly, but r.read() is always NULL. I can say it's not a problem in how the request is made, because content-length header is greater than zero on server side.

文档说 r是实现可读流的http.IncomingMessage对象界面,为什么它不起作用?

Documentation says r is a http.IncomingMessage object that implements the Readable Stream interface, so why it's not working?

推荐答案

好的,我想我已经找到了解决方案. r流(就像node.js中的其他所有内容一样,我很愚蠢……)应该以异步事件驱动的方式读取:

Ok, I think I've found the solution. The r stream (like everything else in node.js, stupid me...) should be read in an async event-driven way:

http.createServer(function(r, s) {
    console.log(r.method, r.url, r.headers);
    var body = "";
    r.on('readable', function() {
        body += r.read();
    });
    r.on('end', function() {
        console.log(body);
        s.write("OK"); 
        s.end(); 
    });
}).listen(42646);

这篇关于从node.js的http.IncomingMessage获取请求正文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆