2013-04-22 23 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