我正在處理一個涉及在另一個服務前使用node.js作爲代理服務器的狡猾計劃。node.js http.request事件流 - 我的END事件發生在哪裏?
簡而言之:
- 調度傳入請求靜態文件(如果存在的話)
- 否則,將請求調度到另一個服務
我有基礎的工作,但現在試圖讓整個事情與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,proxyResponse是否仍會完成?
GET不會觸發END事件,或者END被捕獲到連接堆棧的某個地方是正常的嗎?
'finish'事件似乎按照建議[here](http://stackoverflow.com/a/18255507) – 2015-01-21 14:12:45