当我的Node.js Express服务器(正在侦听端口3000)收到请求时,它会路由到一个必须向另一个网站发出POST并在响应初始请求之前获得响应的函数。
这可能吗?
app.get('/silence/:host', routes.silence);
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
exports.silence = function(request, response){
var hostname = utils.validateHost(request);
if (stash.createSilencer(hostname)) {
response.writeHead(200, {"Content-Type": "application/json"});
response.write('{ "success" : true, "message" : "Successfully silenced host'" }');
response.end();
}
}
exports.createSilencer = function(hostname) {
var options = {
url: 'http://x.x.com:4567/create/silencer/' + hostname ,
method: 'POST',
body: '{ "timestamp": ' + utils.timestamp() + '} '
};
request(options, silencer_callback);
##### DONT WANT TO RETURN UNTIL THE silencer_callback IS INVOKED
return true;
}
function silencer_callback(error, response, body) {
if (!error && response.statusCode == 200) {
var info = JSON.parse(body);
console.log("Response Recieved");
}
}
答案 0 :(得分:0)
诀窍是,在收到POST请求的响应之前,您不会调用response.write()
和response.end()
。您只需退出方法而不发送回复。一旦有了POST请求的结果,就可以完成初始响应。
exports.silence = function(req, res){
var hostname = utils.validateHost(req);
stash.createSilencer(hostname, function(error, response, body) {
if (!error && response.statusCode == 200) {
var info = JSON.parse(body);
console.log("Response Received");
}
// we get POST-response, lets response to initial request here
res.writeHead(200, {"Content-Type": "application/json"});
res.write('{ "success" : !error, "message" : "Successfully silenced host'" }');
res.end();
});
// return from the function, but do not send response back yet
}
exports.createSilencer = function(hostname, callback) {
var options = {
url: 'http://x.x.com:4567/create/silencer/' + hostname ,
method: 'POST',
body: '{ "timestamp": ' + utils.timestamp() + '} '
};
request(options, callback);
// return from the function, but do not send response back yet
}