在下面的代码中,我无法理解为什么 req.pipe(res) 不起作用,但也不会抛出错误。我的直觉告诉我这是由于 Node.js 的异步行为导致的,但这是一个非常简单的情况,没有回调函数。
我错过了什么?
以下是调试输出(请注意,已上传正文):
此外,当我使用大请求体进行压力测试时,会出现EPIPE错误。如何避免这种情况?
-- 编辑:通过试错,我成功解决了这个问题,它仍然指向一个时间问题。虽然这很奇怪,因为超时会导致有效载荷被返回,但超时持续时间并不重要。换句话说,无论我将超时设置为5秒还是500秒,有效载荷都会正确地传回请求,连接也会被终止。
以下是编辑内容:
我错过了什么?
http.createServer(function (req, res) {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.write('Echo service: \nUrl: ' + req.url);
res.write('\nHeaders:\n' + JSON.stringify(req.headers, true, 2));
res.write('\nBody:\n');
req.pipe(res); // does not work
res.end();
}).listen(8000);
以下是 curl 命令:
➜ ldap-auth-gateway git:(master) ✗ curl -v -X POST --data "test.payload" --header "Cookie: token=12345678" --header "Content-Type:text/plain" localhost:9002
以下是调试输出(请注意,已上传正文):
About to connect() to localhost port 9002 (#0)
Trying 127.0.0.1...
connected
Connected to localhost (127.0.0.1) port 9002 (#0)
POST / HTTP/1.1
User-Agent: curl/7.24.0 (x86_64-apple-darwin12.0) libcurl/7.24.0 OpenSSL/0.9.8x zlib/1.2.5
Host: localhost:9002
Accept: */*
Cookie: token=12345678
Content-Type:text/plain
Content-Length: 243360
Expect: 100-continue
HTTP/1.1 100 Continue
HTTP/1.1 200 OK
Content-Type: text/plain
Date: Sun, 04 Aug 2013 17:12:39 GMT
Connection: keep-alive
Transfer-Encoding: chunked
服务响应时不会回显请求体:
Echo service:
Url: /
Headers:
{
"user-agent": "curl/7.24.0 (x86_64-apple-darwin12.0) libcurl/7.24.0 OpenSSL/0.9.8x zlib/1.2.5",
"host": "localhost:9002",
"accept": "*/*",
"cookie": "token=12345678",
"content-type": "text/plain",
"content-length": "243360",
"expect": "100-continue"
}
...最后的curl调试信息如下:
Body:
Connection #0 to host localhost left intact
Closing connection #0
此外,当我使用大请求体进行压力测试时,会出现EPIPE错误。如何避免这种情况?
-- 编辑:通过试错,我成功解决了这个问题,它仍然指向一个时间问题。虽然这很奇怪,因为超时会导致有效载荷被返回,但超时持续时间并不重要。换句话说,无论我将超时设置为5秒还是500秒,有效载荷都会正确地传回请求,连接也会被终止。
以下是编辑内容:
http.createServer(function (req, res) {
try {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.write('Echo service: ' + req.url + '\n' + JSON.stringify(req.headers, true, 2));
res.write('\nBody:"\n');
req.pipe(res);
} catch(ex) {
console.log(ex);
// how to change response code to error here? since headers have already been written?
} finally {
setTimeout((function() {
res.end();
}), 500000);
}
}).listen(TARGET_SERVER.port);
?