2013-04-22 48 views
1

我使用Node-Soap库调用从我的node.js服务器外部网络serivce自定义服务器响应发送到客户端,如下图所示代码:如何从node.js的

var http = require("http"); 
var soap = require("soap"); 
var url = 'http://www.w3schools.com/webservices/tempconvert.asmx?wsdl'; 
var args = {Celsius: '40'}; 

http.createServer(function(request,response) { 
    response.writeHead(200,{"Content-Type":"text/html"}); 
    response.write("<h1>Hello, Web!</h1>"); 
    soap.createClient(url, function(err, client) { 
    client.CelsiusToFahrenheit(args, function(err, result) { 
     console.log(result); //This works 
     response.write(result); //This doesn't print 
    }); 
    }); 
    response.end(); 
}).listen(8888); 

我能够成功地调用Web服务并能够获得响应。问题是,当我使用的console.log()我能得到输出打印result

{ CelsiusToFahrenheitResult: '104' } 

但是当我通过的Response.Write发送它,我不能得到任何输出,我会获得空白值。我试着给result.toString()JSON.stringify(result),但我仍然空白。

你能帮我吗?为什么我能够使用console.log打印数据但不使用response.write?

回答

1

您应该结束你的SOAP请求完成后,才应答(你创建SOAP客户端后,立即结束,但SOAP请求的结果之前,可能需要一段时间可用):

http.createServer(function(request,response) { 
    response.writeHead(200,{"Content-Type":"text/html"}); 
    response.write("<h1>Hello, Web!</h1>"); 
    soap.createClient(url, function(err, client) { 
    client.CelsiusToFahrenheit(args, function(err, result) { 
     ...convert result to string-form, perhaps with JSON.stringify()... 
     response.end(result); 
    }); 
    }); 
}).listen(8888); 

有几件事情需要注意:

  • response.end()可以采取数据为好,所以没有必要(在这种情况下)使用一个单独的response.write();
  • end()需要data参数为一个字符串或Buffer;
+0

感谢您的回复,按照我的说法,我将代码更改为'var s = JSON.stringify(result); response.end(s);'但我仍然只获取Hello,Web!不是结果的值:( – 2013-04-22 11:15:49

+0

这很奇怪;我没有可以使用的SOAP服务器,所以我使用'setTimeout'来测试,而且工作得很好,你确实删除了旧的'response.end',对吗?这里是我的测试代码:https://gist.github.com/robertklep/5434012) – robertklep 2013-04-22 11:18:46

+0

是的,我确实删除了它,但仍然没有白费。你是如何设置时间的?如果可能请分享该代码? – 2013-04-22 11:20:01