我正在使用Node-Soap从我的node.js服务器调用外部Web服务的库,代码如下所示:
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);
我能够成功调用网络服务并能够得到响应。问题是当我使用 console.log() 打印结果
时,我能够得到输出为:
{ CelsiusToFahrenheitResult: '104' }
但是当我通过response.write发送它时,我无法获得任何输出,我将得到空白值。我尝试给出 result.toString()
和 JSON.stringify(result)
但我仍然一片空白。
你能帮我一下吗?为什么我可以使用console.log打印数据,但不能使用response.write打印数据?
最佳答案
您应该仅在 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()
期望数据参数是字符串或Buffer
;
关于javascript - 如何从 Node.js 自定义服务器向客户端发送响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16145305/