我正在使用一个路由来处理网址。功能按预期启动。我想要做的是在回调中使用response.write()。我知道这不起作用,因为回调不能访问与调用它的函数相同的变量,但我想知道正确的NODE方式是做什么的。
route.post('/{type}subject/{method}', function (request,response) {
var post = "";
request.on('data', function (chunk){
post += chunk;
});
request.on('end', function (){
postData = qs.parse(post);
response.writeHead(200);
switch(request.params['method'].toLowerCase())
{
case "registerobserver":
if (postData['uri']){
registerObserver (request.params['type'], postData['uri']);
response.write(success("registerobserver"));
}
else
response.write(failure("1","uri undefined"));
break;
case "unregisterobserver":
if (postData['uri']){
client.query ('DELETE observers FROM observers INNER JOIN type ON (observers.TypeID = type.TypeID) WHERE observers.uri ="'+postData['uri']+'" AND type.name = "'+request.params['type']+'"',
function(err, info)
{
if(err){
response.write(failure("2", "general database failure"));}
else{
if(info.affectedRows != 0)
response.write(success("unregisterobserver")); //this code does not trigger a response due to namespace
else
response.write(failure("1", "uri not an observer"));//this code does not trigger a response
console.log("uri not observer");
}
console.log("done");
})
}
else
response.write(failure("1","uri required"));
break;
default:
}
response.end();
})
//response.write("type: "+request.params['type']+"<br/>method="+request.params['method']);
});
function success(method){return "<?xml version=\"1.0\"?>\n<response stat=\"ok\">\n\t<method>"+method+"</method>\n</response>";}
function failure(code, message){return "<?xml version=\"1.0\"?>\n<response stat=\"fail\">\n\t<err code=\""+code+"\" msg = \""+message+"\" />\n</response>";}
答案 0 :(得分:7)
基本上发生的事情是,在 query
函数调用之后,异步response.end()
处理函数将被称为。因此,任何写入都将失败。
您需要从回调内部调用response.end()
,并且在处于异步代码路径时请注意不要再调用response.end()
。 IE浏览器。 return
致电后立即client.query()
。