我正在尝试以String或Buffer的形式将HTTP响应解析为Object. 结果将是一个像本机http模块的响应一样的对象. 我尝试导入本机HTTP解析器,但结果对于我的用例来说太原始了: var HTTPParser
结果将是一个像本机http模块的响应一样的对象.
我尝试导入本机HTTP解析器,但结果对于我的用例来说太原始了:
var HTTPParser = process.binding('http_parser').HTTPParser; var parser = new HTTPParser(HTTPParser.RESPONSE); parser.onHeadersComplete = function(res) { console.log('onHeadersComplete'); console.log(res); }; parser.execute(data, 0, data.length);
这会返回这样的东西:
onHeadersComplete { headers: [ 'X-Powered-By', 'Express', 'Content-Type', 'text/plain', 'Content-Length', '2', 'Date', 'Sat, 19 Apr 2014 20:16:45 GMT', 'Connection', 'keep-alive' ], statusCode: 200, versionMajor: 1, versionMinor: 1, shouldKeepAlive: true, upgrade: false }
我的用例缺少两件事:
>与标题值关联的标题名称的映射
>解析响应体
>有谁知道如何实现这一目标?
预先感谢您的帮助 !
你必须填写所有的回调.var HTTPParser = require('http-parser-js').HTTPParser; var parser = new HTTPParser(HTTPParser.RESPONSE); parser.onHeadersComplete = function(res) { console.log(res.headers); }; parser.onBody = function(chunk, offset, length) { console.log("body", chunk.toString(), offset, length) } parser.onMessageComplete = function() { } parser.execute(new Buffer('HTTP/1.1 200 OK\r\nContent-Type: text/plain; xya\r\nContent-Length: 11\r\n\r\nhello world'))