在 Node.js 上调用 WCF Web 服务

摘要:有时我们需要在WCF中做一些复杂数据处理和逻辑判断等,这时候就需要在NodeJS中调用WCF服务获取数据,这篇文件介绍如何在Node中调用WCF服务获取数据。

Node项目中调用WCF服务获取数据,通常需要将获取到的table或list类型数据转为json格式,来调用回调函数向前台显示数据。以下代码显示如何调用wcf服务及如何将数据转为json类型。
wcf服务发布后的地址如:http://localhost:3721/service/IsAuth

需要添加的引用如下:

var xpath = require('xpath.js');
var dom = require('xmldom').DOMParser;

声明代理及拼接要发送的数据:

var BasicHttpBinding = require('wcf.js').BasicHttpBinding,
    Proxy = require('wcf.js').Proxy,
    binding = new BasicHttpBinding(),
    proxy = new Proxy(binding, 'http://localhost:3721/service'),
    message = "<Envelope xmlns='http://schemas.xmlsoap.org/soap/envelope/'>" +
        "<Header />" +
        "<Body>" +
        "<LoginVer xmlns='http://tempuri.org/'>" +
        "<name>admin</name><pwd>123456</pwd>"+//成对的参数
        "</LoginVer>" +
        "</Body>" +
"</Envelope>";

发送数据,并根据不同的返回类型转换数据为json:

proxy.send(message, "http://tempuri.org/service/IsAuth", function (response, ctx) {
    if (ctx && ctx.error) {
        callback(ctx.error, '');
        return;
    }

    if(response.indexOf('s:Envelope')>0) {
        if (response.indexOf('xs:schema') > 0) {
            //返回数据为Table
            var start = response.indexOf('<DocumentElement');
            var end = response.indexOf('</DocumentElement>');
            if(start == -1){
                callback(null,{table:[]});
            }else{
                var datas = response.slice(start, end + 18);
                converttabletojson(datas, function (err, data) {
                    callback(err, data);
                });
            }
        }
        else{
            //返回数据为List
            var start = response.indexOf('<' + method + 'Result');
            var end = response.indexOf('</' + method + 'Response');
            if(end == -1){
                callback(null,{list:[]});
            }else{
                var datas = response.slice(start, end);
                convertlisttojson(datas, method + 'Result', function (err, data) {
                    callback(err, data);
                });
            }
        }
    }
    else{
        callback(new Error('404,Not Found Page'));
    }

});

返回数据为Table时,将Table转为json方法:

function converttabletojson(table, callback) {
    try {
        var doc = new dom().parseFromString(table), jsonr = [];
        var nodes = xpath(doc, '/DocumentElement/*');
        nodes.forEach(function (item) {
            var row = {};
            var childs = item.childNodes;
            for (var key in childs) {
                if (childs[key].localName) {
                    var name = childs[key].localName;
                    var value = childs[key].firstChild != null ? childs[key].firstChild.data : ' ';
                    row[name] = value;
                }
            };
            jsonr.push(row);
        });
        doc = null;
        nodes = null;
        callback(null, {table: jsonr});
    } catch (err) {
        doc = null;
        nodes = null;
        callback(err);
    }
};

返回数据为List时,将List转为json方法:

function convertlisttojson(lists,root, callback) {
    try {
        var doc = new dom().parseFromString(lists), jsonr = {};
        var childdoc = doc.childNodes[0].childNodes;
        for(var i =0;i<childdoc.length;i++){
            var rows = [];
            if(!childdoc[i].firstChild){
                if(typeof childdoc[i].data === 'string'){
                    jsonr['mydata'] = jsonr['mydata'] || [];
                    jsonr['mydata'].push(childdoc[i].data);
                }
                continue;
            }else if(typeof childdoc[i].firstChild.data === 'string'){
                jsonr['mydata'] = jsonr['mydata'] || [];
                jsonr['mydata'].push(childdoc[i].firstChild.data );
                continue;
            }
            var lsttagname = childdoc[i].firstChild.tagName,
                lstname = lsttagname.substr(lsttagname.indexOf(':')+1);
            if(lstname){
                var lsts = childdoc[i].getElementsByTagName(lsttagname);
                for(var j =0;j<lsts.length;j++){
                    var item = lsts[j];
                    var childs = item.childNodes, row={};
                    for(var key in childs){
                        if(childs[key].localName) {
                            var name = childs[key].localName;
                            var value = childs[key].firstChild.data;
                            row[name] = value;
                        }
                    };
                    rows.push(row);
                }
                jsonr[lstname] = rows;
            }
        }
        doc = null;nodes =null;
        callback(null,{list:[jsonr]});
    }catch(err){
        doc = null;nodes =null;
        callback(err);
    }
};

以上两个方法是根据wcf返回不同的数据类型做相应的判断。以下是返回两种类型的数据的示例:

List:

<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
  <s:Body>
     <IsAuthResponse xmlns="http://tempuri.org/">
         <IsAuthResult>yes</IsAuthResult>
     </IsAuthResponse>
  </s:Body>
</s:Envelope>

   Table:

<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
  <s:Body>
   <GetDataResponse xmlns="http://tempuri.org/">
   <GetDataResult xmlns:a="http://schemas.datacontract.org/2004/07/Model" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
     <a:scoreValue>
       <a:ScoreValue><a:name>语文</a:name> <a:value>90</a:value> </a:ScoreValue>
       <a:ScoreValue><a:name>数学</a:name><a:value>92</a:value></a:ScoreValue>
       <a:ScoreValue><a:name>英语</a:name><a:value>83</a:value></a:ScoreValue>
     </a:scoreValue>
   </GetDataResult>
   </GetDataResponse>
  </s:Body>
</s:Envelope>
鉴于写作能力有限,若有描述不当或明显错误的,欢迎指正!
原文地址:https://www.cnblogs.com/wonglu/p/5022337.html