Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/url/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js:如何使用SOAP XML web服务_Xml_Node.js_Soap - Fatal编程技术网

Node.js:如何使用SOAP XML web服务

Node.js:如何使用SOAP XML web服务,xml,node.js,soap,Xml,Node.js,Soap,我想知道使用node.js使用SOAP XML web服务的最佳方式是什么 谢谢 你没有那么多选择 您可能需要使用以下选项之一: (重写节点soap) 我认为另一种选择是: 使用诸如SoapUI()之类的工具来记录输入和输出xml消息 使用node request()形成输入xml消息,将请求发送(POST)到web服务(注意,标准javascript模板机制,如ejs()或mustache()在这里可以帮助您),最后 使用XML解析器将响应数据反序列化为JavaScript对象 是的

我想知道使用node.js使用SOAP XML web服务的最佳方式是什么


谢谢

你没有那么多选择

您可能需要使用以下选项之一:

  • (重写
    节点soap

    • 我认为另一种选择是:

      • 使用诸如SoapUI()之类的工具来记录输入和输出xml消息
      • 使用node request()形成输入xml消息,将请求发送(POST)到web服务(注意,标准javascript模板机制,如ejs()或mustache()在这里可以帮助您),最后
      • 使用XML解析器将响应数据反序列化为JavaScript对象

      是的,这是一个相当肮脏和低级的方法,但它应该可以毫无问题地工作

      您也可以看看easysoap npm- -或-


      根据需要的端点数量,手动操作可能更容易

      我已经尝试了10个库“soapnodejs”,我终于手动完成了

      • 使用node request()形成输入xml消息,以将请求发送(POST)到web服务
      • 使用xml2j()解析响应
      我在10多个跟踪WebAPI(Tradetracker、Bbelboon、Affilinet、Webgains等)上成功地使用了“soap”包()

      问题通常来自这样一个事实:程序员不太了解远程API需要什么来连接或验证


      例如,PHP自动从HTTP头重新发送cookie,但在使用“节点”包时,必须显式设置它(例如通过“soap cookie”包)

      我使用node net模块打开Web服务的套接字

      /* on Login request */
      socket.on('login', function(credentials /* {username} {password} */){   
          if( !_this.netConnected ){
              _this.net.connect(8081, '127.0.0.1', function() {
                  logger.gps('('+socket.id + ') '+credentials.username+' connected to: 127.0.0.1:8081');
                  _this.netConnected = true;
                  _this.username = credentials.username;
                  _this.password = credentials.password;
                  _this.m_RequestId = 1;
                  /* make SOAP Login request */
                  soapGps('', _this, 'login', credentials.username);              
              });         
          } else {
              /* make SOAP Login request */
              _this.m_RequestId = _this.m_RequestId +1;
              soapGps('', _this, 'login', credentials.username);          
          }
      });
      
      发送soap请求

      /* SOAP request func */
      module.exports = function soapGps(xmlResponse, client, header, data) {
          /* send Login request */
          if(header == 'login'){
              var SOAP_Headers =  "POST /soap/gps/login HTTP/1.1\r\nHost: soap.example.com\r\nUser-Agent: SOAP-client/SecurityCenter3.0\r\n" +
                                  "Content-Type: application/soap+xml; charset=\"utf-8\"";        
              var SOAP_Envelope=  "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
                                  "<env:Envelope xmlns:env=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:SOAP-ENC=\"http://www.w3.org/2003/05/soap-encoding\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:n=\"http://www.example.com\"><env:Header><n:Request>" +
                                  "Login" +
                                  "</n:Request></env:Header><env:Body>" +
                                  "<n:RequestLogin xmlns:n=\"http://www.example.com.com/gps/soap\">" +
                                  "<n:Name>"+data+"</n:Name>" +
                                  "<n:OrgID>0</n:OrgID>" +                                        
                                  "<n:LoginEntityType>admin</n:LoginEntityType>" +
                                  "<n:AuthType>simple</n:AuthType>" +
                                  "</n:RequestLogin></env:Body></env:Envelope>";
      
              client.net.write(SOAP_Headers + "\r\nContent-Length:" + SOAP_Envelope.length.toString() + "\r\n\r\n");
              client.net.write(SOAP_Envelope);
              return;
          }
      

      希望它能帮助某人

      我发现使用Node.js将原始XML发送到SOAP服务的最简单方法是使用Node.js http实现。看起来像这样

      var http = require('http');
      var http_options = {
        hostname: 'localhost',
        port: 80,
        path: '/LocationOfSOAPServer/',
        method: 'POST',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
          'Content-Length': xml.length
        }
      }
      
      var req = http.request(http_options, (res) => {
        console.log(`STATUS: ${res.statusCode}`);
        console.log(`HEADERS: ${JSON.stringify(res.headers)}`);
        res.setEncoding('utf8');
        res.on('data', (chunk) => {
          console.log(`BODY: ${chunk}`);
        });
      
        res.on('end', () => {
          console.log('No more data in response.')
        })
      });
      
      req.on('error', (e) => {
        console.log(`problem with request: ${e.message}`);
      });
      
      // write data to request body
      req.write(xml); // xml would have been set somewhere to a complete xml document in the form of a string
      req.end();
      
      您可以将xml变量定义为字符串形式的原始xml


      但是,如果您只想通过Node.js与SOAP服务交互并进行常规SOAP调用,而不是发送原始xml,那么请使用Node.js库之一。我喜欢。

      我设法使用了soap、wsdl和Node.js 您需要使用
      npm安装soap安装soap

      创建一个名为
      server.js
      的节点服务器,它将定义远程客户端要使用的soap服务。此soap服务根据体重(kg)和身高(m)计算体重指数

      接下来,创建一个
      client.js
      文件,该文件将使用
      server.js
      定义的soap服务。该文件将为soap服务提供参数,并使用soap的服务端口和端点调用url

      const express = require('express');
      const soap = require('soap');
      const url = 'http://localhost:3030/bmicalculator?wsdl';
      const args = { weight: 65.7, height: 1.63 };
      soap.createClient(url, function(err, client) {
        if (err) console.error(err);
        else {
          client.calculateBMI(args, function(err, response) {
            if (err) console.error(err);
            else {
              console.log(response);
              res.send(response);
            }
          });
        }
      });
      
      您的wsdl文件是用于数据交换的基于xml的协议,它定义了如何访问远程web服务。调用您的wsdl文件
      bmicaller.wsdl

      <definitions name="HelloService" targetNamespace="http://www.examples.com/wsdl/HelloService.wsdl" 
        xmlns="http://schemas.xmlsoap.org/wsdl/" 
        xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" 
        xmlns:tns="http://www.examples.com/wsdl/HelloService.wsdl" 
        xmlns:xsd="http://www.w3.org/2001/XMLSchema">
      
        <message name="getBMIRequest">
          <part name="weight" type="xsd:float"/>
          <part name="height" type="xsd:float"/>
        </message>
      
        <message name="getBMIResponse">
          <part name="bmi" type="xsd:float"/>
        </message>
      
        <portType name="Hello_PortType">
          <operation name="calculateBMI">
            <input message="tns:getBMIRequest"/>
            <output message="tns:getBMIResponse"/>
          </operation>
        </portType>
      
        <binding name="Hello_Binding" type="tns:Hello_PortType">
          <soap:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http"/>
          <operation name="calculateBMI">
            <soap:operation soapAction="calculateBMI"/>
            <input>
              <soap:body encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" namespace="urn:examples:helloservice" use="encoded"/>
            </input>
            <output>
              <soap:body encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" namespace="urn:examples:helloservice" use="encoded"/>
            </output>
          </operation>
        </binding>
      
        <service name="BMI_Service">
          <documentation>WSDL File for HelloService</documentation>
          <port binding="tns:Hello_Binding" name="BMI_Port">
            <soap:address location="http://localhost:3030/bmicalculator/" />
          </port>
        </service>
      </definitions>
      
      
      HelloService的WSDL文件
      

      如果
      节点soap
      对您不起作用,只需使用
      节点
      请求模块,然后根据需要将xml转换为json即可

      我的请求不适用于
      节点soap
      ,除了付费支持之外,没有对该模块的支持,这超出了我的资源范围。因此,我做了以下工作:

    • 在我的Linux机器上下载
    • 已将WSDL xml复制到本地文件
      curlhttp://192.168.0.28:10005/MainService/WindowsService?wsdl >wsdl_file.xml
    • 在SoapUI中,我转到
      文件>新的Soap项目
      ,并上传了我的
      wsdl\u File.xml
    • 在导航器中,我展开了其中一个服务并右键单击 打开请求并单击
      显示请求编辑器
    • 从那里,我可以发送一个请求并确保它有效,我还可以使用
      Raw
      HTML
      数据来帮助我构建一个外部请求

      根据我的请求从SoapUI获取原始数据

      POST http://192.168.0.28:10005/MainService/WindowsService HTTP/1.1
      Accept-Encoding: gzip,deflate
      Content-Type: text/xml;charset=UTF-8
      SOAPAction: "http://Main.Service/AUserService/GetUsers"
      Content-Length: 303
      Host: 192.168.0.28:10005
      Connection: Keep-Alive
      User-Agent: Apache-HttpClient/4.1.1 (java 1.5)
      
      来自SoapUI的XML

      <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:qtre="http://Main.Service">
         <soapenv:Header/>
         <soapenv:Body>
            <qtre:GetUsers>
               <qtre:sSearchText></qtre:sSearchText>
            </qtre:GetUsers>
         </soapenv:Body>
      </soapenv:Envelope> 
      
      添加到:您可以添加
      preservewitspace=true
      ,以避免出现空白错误。像这样:

      soap.CreateClient(url,preserveWhitespace=true,function(...){
      

      您也可以使用wsdlrdr。EasySoap基本上是用一些额外的方法重写wsdlrdr。
      请注意,easysoap没有wsdlrdr上提供的getNamespace方法。

      对于那些刚接触
      SOAP
      并希望快速了解和指导的人,我强烈推荐这种很棒的媒体


      您还可以使用
      节点soap
      ,方法很简单。

      如果您只需要一次性转换,可以通过创建一个免费帐户来实现这一点(没有附属关系,它只对我有用)

      如果您转换为Swagger 2.0,您可以使用

      $ wget https://repo1.maven.org/maven2/io/swagger/codegen/v3/swagger-codegen-cli/3.0.20/swagger-codegen-cli-3.0.20.jar \
        -O swagger-codegen-cli.jar
      $ java -jar swagger-codegen-cli.jar generate \
        -l javascript -i orig.wsdl-Swagger20.json -o ./fromswagger
      

      在我看来,避免使用nodejs查询soapis

      两个备选方案:

    • 如果您是SOAP API的所有者,请让它同时处理xml和json请求,因为javascript可以很好地处理json

    • 在php中实现API网关(因为php可以很好地处理SOAP)。网关将以json的形式接收您的输入,然后以xml查询SOAP API,并将xml响应转换为json


    • 谢谢由于node expat安装失败,导致node soap安装出现问题=(你需要expat开发标题来构建itI,我发现了标题的问题,但我不知道应该从哪里获取,应该把它放在哪里编译,请解释一下,也许你可以通过操作系统的包管理工具获取它们。例如,在Ubuntu上
      sudo apt get install libexpat1 dev
      @RobertBroden,th.)请下次继续编辑答案(或建议编辑)!遗憾的是,这是使用Node.js与SOAP交互的最可靠的方法。我还没有找到一个SOAP库,可以在我必须使用的少数API上正确地发出SOAP请求。100%脏,但这让我感到很不舒服
      var request = require('request');
      let xml =
      `<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:qtre="http://Main.Service">
         <soapenv:Header/>
         <soapenv:Body>
            <qtre:GetUsers>
               <qtre:sSearchText></qtre:sSearchText>
            </qtre:GetUsers>
         </soapenv:Body>
      </soapenv:Envelope>`
      
      var options = {
        url: 'http://192.168.0.28:10005/MainService/WindowsService?wsdl',
        method: 'POST',
        body: xml,
        headers: {
          'Content-Type':'text/xml;charset=utf-8',
          'Accept-Encoding': 'gzip,deflate',
          'Content-Length':xml.length,
          'SOAPAction':"http://Main.Service/AUserService/GetUsers"
        }
      };
      
      let callback = (error, response, body) => {
        if (!error && response.statusCode == 200) {
          console.log('Raw result', body);
          var xml2js = require('xml2js');
          var parser = new xml2js.Parser({explicitArray: false, trim: true});
          parser.parseString(body, (err, result) => {
            console.log('JSON result', result);
          });
        };
        console.log('E', response.statusCode, response.statusMessage);  
      };
      request(options, callback);
      
      soap.CreateClient(url,preserveWhitespace=true,function(...){
      
      $ wget https://repo1.maven.org/maven2/io/swagger/codegen/v3/swagger-codegen-cli/3.0.20/swagger-codegen-cli-3.0.20.jar \
        -O swagger-codegen-cli.jar
      $ java -jar swagger-codegen-cli.jar generate \
        -l javascript -i orig.wsdl-Swagger20.json -o ./fromswagger