gpt4 book ai didi

javascript - Node.js HTTP 字符串

转载 作者:行者123 更新时间:2023-11-30 05:37:00 26 4
gpt4 key购买 nike

给定一个完整的 HTTP 消息字符串,Node.js 中是否有工具来解析它?基本上我不会使用 http.createServer 函数。我已经通过其他方式 (ZMQ) 获得了完整的 HTTP 消息,但我需要解析它,这意味着 header 、查询字符串、帖子正文等。

此外,同样的功能应该能够逆转这个过程,即创建一个完整的 HTTP 响应消息字符串。我可以使用和通过不同的交通工具 (ZMQ)。

我知道 PHP 有 Symfony's HTTP Foundation (这符合我的要求)。 Node.js 中是否有类似的功能?

我找到了这个:https://github.com/joyent/http-parser但它是在 C++ 中

最佳答案

您可以在 node 中使用 http-parser,但没有很好的文档记录。我从 the tests 中提取了以下示例:

var HTTPParser = process.binding('http_parser').HTTPParser,
CRLF = '\r\n',
request = new Buffer('POST /it HTTP/1.1' + CRLF +
'Content-Type: application/x-www-form-urlencoded' + CRLF +
'Content-Length: 15' + CRLF +
CRLF +
'foo=42&bar=1337'),
parser = new HTTPParser(HTTPParser.REQUEST),
headers = {},
body = '';

parser.onHeadersComplete = function(info) {
headers = info;
};

parser.onBody = function(b, start, len) {
body = b.slice(start, start + len).toString();
};

parser.onMessageComplete = function() {
console.log('message complete');
console.log('request method: ' + headers.method);
console.log('request body:\n\n ' + body);
};

parser.execute(request, 0, request.length);

给出以下输出:

message complete
request method: POST
request body:

foo=42&bar=1337

关于javascript - Node.js HTTP 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23081788/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com