Tob*_*ede 3 javascript proxy connect node.js coffeescript
我正在制定一个狡猾的计划,该计划涉及使用 node.js 作为另一个服务前的代理服务器。
简而言之:
我有基本的工作,但现在试图让整个事情与 Sencha Connect一起工作,这样我就可以访问提供的所有中间件。
所有的动作都发生在下面的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()
Run Code Online (Sandbox Code Playgroud)
您会在上面的最后一行注意到proxyRequest.end()。
我发现在处理 GET 请求时,永远不会触发请求的 END 事件,因此需要调用 proxyRequest.end() 。POST 请求会按预期触发 DATA 和 END 事件。
所以几个问题:
这个调用 proxyRequest.end() 安全吗?也就是说,即使在事件循环之外调用它,proxyResponse 是否仍会完成?
GET 不触发 END 事件是否正常,或者 END 是否在连接堆栈中的某处被捕获?
问题是end事件少,事件多data。如果客户端发出 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/');
Run Code Online (Sandbox Code Playgroud)
如果我对该服务器进行 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()
Run Code Online (Sandbox Code Playgroud)
所以是的proxyRequest.end(),GET由于我刚刚提到的逻辑分支,您将不得不手动调用请求。
| 归档时间: |
|
| 查看次数: |
5857 次 |
| 最近记录: |