[英]NodeJS response.write inside callback
I'm using a route to process a url. 我正在使用一个路由来处理网址。 The functions fire as expected.
功能按预期启动。 What I'm trying to do is use the response.write() inside of a call back.
我想要做的是在回调中使用response.write()。 I understand this isn't working because the call back doesn't have access to the same variables as the function that calls it, but I'm wondering what the correct NODE way of doing this would be.
我知道这不起作用,因为回调不能访问与调用它的函数相同的变量,但我想知道正确的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>";}
Basically what happens is that the async query
handler function will be called after your response.end()
function call. 基本上发生的是在
response.end()
函数调用之后将调用异步query
处理函数。 As such any writes will fail. 因此,任何写入都将失败。
You need to call response.end()
from inside the callback instead, and take care to not otherwise call response.end()
once you are in async code path. 您需要从回调内部调用
response.end()
,并且在处于异步代码路径时请注意不要另外调用response.end()
。 Ie. IE浏览器。
return
immediately after the client.query()
call. 在
client.query()
调用之后立即return
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.