I am working on a cunning plan that involves using node.js as a proxy server in front of another service.
In short:
- Dispatch incoming request to a static file (if it exists)
- Otherwise, dispatch the request to another service
I have the basics working, but now attempting to get the whole thing working with Sencha Connect so I can access all the kick-ass middleware provided.
All of the action happens in dispatchProxy below
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()
You will notice proxyRequest.end() on the final line above.
What I have found is that when handling GET requests, the END event of the request is never triggered and therefore a call to proxyRequest.end() is required. POST requests trigger both DATA and END events as expected.
So several questions:
Is this call to proxyRequest.end() safe? That is, will the proxyResponse still be completed even if this is called outside of the event loops?
Is it normal for GET to not trigger END events, or is the END being captured somewhere in the connect stack?
finish
event seems to work as suggested here – Erelong