javascript-node.js http.request事件流-我的END事件去了哪里?
作者:互联网
我正在制定一个狡猾的计划,其中涉及将node.js用作另一个服务之前的代理服务器.
简而言之:
>将传入请求分派到静态文件(如果存在)
>否则,将请求分派到另一个服务
我已经掌握了基础知识,但是现在尝试使Sencha Connect完全正常工作,以便可以访问所提供的所有kick-ass中间件.
所有动作都发生在下面的dispatchProxy中
connect(
connect.logger(),
connect.static(__dirname + '/public'),
(request, response) ->
dispatchProxy(request, response)
).listen(8000)
dispatchProxy = (request, response) ->
options = {host: host, port: port, method: request.method, headers: request.headers, path: request.url}
proxyRequest = http.request(options, (proxyResponse) ->
proxyResponse.on('data', (chunk) ->
response.write(chunk, 'binary')
)
proxyResponse.on('end', (chunk) ->
response.end()
)
response.writeHead proxyResponse.statusCode, proxyResponse.headers
)
request.on('data', (chunk) ->
proxyRequest.write(chunk, 'binary')
)
# this is never triggered for GETs
request.on('end', ->
proxyRequest.end()
)
# so I have to have this here
proxyRequest.end()
您会在上面的最后一行中注意到proxyRequest.end().
我发现,在处理GET请求时,永远不会触发请求的END事件,因此需要调用proxyRequest.end(). POST请求会按预期触发DATA和END事件.
有几个问题:
>对此proxyRequest.end()的调用安全吗?也就是说,即使在事件循环之外调用了proxyResponse,仍然会完成吗?
> GET不触发END事件是否正常,还是在连接堆栈中的某个位置捕获了END?
解决方法:
问题是结束事件较少,而数据事件较多.如果客户端发出GET请求,则会有标头且没有数据.这与POST不同,在POST中,请求者正在发送数据,因此on(“ data”)处理程序将被命中.因此(请原谅我的JS示例,我对coffeescript不太熟悉):
var http = require('http');
// You won't see the output of request.on("data")
http.createServer(function (request, response) {
request.on("end", function(){
console.log("here");
});
request.on("data", function(data) {
console.log("I am here");
console.log(data.toString("utf8"));
});
response.writeHead(200, {'Content-Type': 'text/plain'});
response.end('Hello World\n');
}).listen(8124);
console.log('Server running at http://127.0.0.1:8124/');
如果我对该服务器进行curl调用,则数据事件将永远不会被命中,因为GET请求只不过是标题.因此,您的逻辑变为:
// okay setup the request...
// However, the callback doesn't get hit until you
// start writing some data or ending the proxyRequest!
proxyRequest = http.request(options, (proxyResponse) ->
// So this doesn't get hit yet...
proxyResponse.on('data', (chunk) ->
response.write(chunk, 'binary')
)
// and this doesn't get hit yet
proxyResponse.on('end', (chunk) ->
// which is why your response.on("end") event isn't getting hit yet
response.end()
)
response.writeHead proxyResponse.statusCode, proxyResponse.headers
)
// This doesn't get hit!
request.on('data', (chunk) ->
proxyRequest.write(chunk, 'binary')
)
// So this isn't going to happen until your proxyRequest
// callback handler gets hit, which hasn't happened because
// unlike POST there's no data in your GET request
request.on('end', ->
proxyRequest.end()
)
// now the proxy request call is finally made, which
// triggers the callback function in your http request setup
proxyRequest.end()
所以是的,由于我刚才提到的逻辑分支,您将不得不为GET请求手动调用proxyRequest.end().
标签:node-js,connect,proxy,coffeescript,javascript 来源: https://codeday.me/bug/20191102/1992295.html