我尝试将String
或Buffer
形式的HTTP响应解析为Object
。
结果将是Object
,就像本机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
}
我的用例缺少两件事:
解析响应正文
提前感谢您的帮助!
答案 0 :(得分:4)
你必须填写所有回调。
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'))
答案 1 :(得分:0)
对于标题转换,您可以使用私有方法http.IncomingMessage(socket)._addHeaderLines(headersArr, headersNumber)
var msg=new http.IncomingMessage()
msg._addHeaderLines(['X-Powered-By',
'Express',
'Content-Type',
'text/plain',
'Content-Length',
'2',
'Date',
'Sat, 19 Apr 2014 20:16:45 GMT',
'Connection',
'keep-alive' ], 10);
console.log(msg);
结果:
IncomingMessage {
...
headers:
{ 'x-powered-by': 'Express',
'content-type': 'text/plain',
'content-length': '2',
date: 'Sat, 19 Apr 2014 20:16:45 GMT',
connection: 'keep-alive' },
rawHeaders:
[ 'X-Powered-By',
'Express',
'Content-Type',
'text/plain',
'Content-Length',
'2',
'Date',
'Sat, 19 Apr 2014 20:16:45 GMT',
'Connection',
'keep-alive' ],
...
}
来自节点来源的使用示例:https://github.com/nodejs/node/blob/master/lib/_http_common.js
答案 2 :(得分:-1)
我也试图研究node.js,我昨天刚刚开始。由于它是一个javascript的东西,这是我建议的解决方案。
我认为这里要解析的对象是' res'参数。
var headers = {};
for (index = 0; index < res.headers.length; index++) {
headers[res.headers[index].replace('-', '')] = res.headers[++index];
}
// or this
for (index = 0; index < res.headers.length; index+=2) {
var headerName = res.headers[index].replace('-', '');
headers[headerName] = res.headers[index + 1];
}
// Note that we removed the '-' in the name since it's an invalid character for property name.
// Access sample.
console.log(headers.ContentType);
console.log(headers['ContentType']);
我希望它能帮到你。