Подтвердить что ты не робот

Node.js: как использовать веб-службу SOAP XML

Интересно, как лучше всего использовать веб-службу SOAP XML с помощью node.js

Спасибо!

4b9b3361

Ответ 1

У вас не так много вариантов.

Вероятно, вы захотите использовать один из:

Ответ 2

Я думаю, что альтернативой было бы:

  • используйте такой инструмент, как SoapUI (http://www.soapui.org), чтобы записывать входные и выходные сообщения xml.
  • используйте node запрос (https://github.com/mikeal/request), чтобы сформировать входное XML-сообщение для отправки (POST) запроса на веб-службу (обратите внимание, что стандартные механизмы шаблона javascript такие как ejs (http://embeddedjs.com/) или усы (https://github.com/janl/mustache.js) могут помочь вам здесь) и, наконец,
  • использовать парсер XML для десериализации данных ответа на объекты JavaScript.

Да, это довольно грязный и низкоуровневый подход, но он должен работать без проблем

Ответ 3

Самый простой способ, по которому я только что отправил необработанный XML в SOAP-сервис с помощью Node.js, - это использовать реализацию 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 в виде строки.

Но если вы просто хотите взаимодействовать с SOAP-сервисом с помощью Node.js и выполнять регулярные SOAP-вызовы, в отличие от отправки raw xml, используйте одну из библиотек Node.js. Мне нравится node-soap.

Ответ 4

Если node-soap не работает для вас, просто используйте модуль request node а затем при необходимости преобразуйте xml в json.

Мой запрос не работал с node-soap и нет поддержки этого модуля, кроме платной поддержки, которая была за пределами моих ресурсов. Итак, я сделал следующее:

  1. скачал SoapUI на моей машине с Linux.
  2. скопировал WSDL xml в локальный файл
    curl http://192.168.0.28:10005/MainService/WindowsService?wsdl > wsdl_file.xml
  3. В SoapUI я зашел в File > New Soap project и загрузил свой wsdl_file.xml.
  4. В навигаторе я развернул одну из служб, щелкнул правой кнопкой мыши запрос и нажал " Show Request Editor.

Оттуда я могу отправить запрос и убедиться, что он работает, а также использовать данные в HTML Raw или HTML чтобы помочь мне построить внешний запрос.

Raw из 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)

XML из SoapUI

<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> 

Я использовал выше для построения следующего request node:

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);

Ответ 5

Мне удалось использовать soap, wsdl и Node.js. Вам нужно установить soap с npm install soap

Создайте сервер узла с именем server.js, который определит службу мыла, которая будет использоваться удаленным клиентом. Эта служба мыла рассчитывает индекс массы тела на основе веса (кг) и роста (м).

const soap = require('soap');
const express = require('express');
const app = express();
/**
 * this is remote service defined in this file, that can be accessed by clients, who will supply args
 * response is returned to the calling client
 * our service calculates bmi by dividing weight in kilograms by square of height in metres
 */
const service = {
  BMI_Service: {
    BMI_Port: {
      calculateBMI(args) {
        //console.log(Date().getFullYear())
        const year = new Date().getFullYear();
        const n = args.weight / (args.height * args.height);
        console.log(n);
        return { bmi: n };
      }
    }
  }
};
// xml data is extracted from wsdl file created
const xml = require('fs').readFileSync('./bmicalculator.wsdl', 'utf8');
//create an express server and pass it to a soap server
const server = app.listen(3030, function() {
  const host = '127.0.0.1';
  const port = server.address().port;
});
soap.listen(server, '/bmicalculator', service, xml);

Затем создайте файл client.js который будет использовать сервис мыла, определенный server.js. Этот файл предоставит аргументы для службы мыла и вызовет URL с портами и конечными точками службы SOAP.

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 протокол обмена данными, который определяет, как получить доступ к удаленному веб-сервису. Позвоните в ваш файл bmicalculator.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>

Надеюсь, поможет

Ответ 6

В зависимости от количества конечных точек вам может быть проще сделать это вручную.

Я попробовал 10 библиотек "мыла nodejs", я, наконец, сделать это вручную.

Ответ 7

Я успешно использовал пакет "soap" (https://www.npmjs.com/package/soap) на более чем 10 отслеживаниях WebApis (Tradetracker, Bbelboon, Affilinet, Webgains,...).

Проблемы обычно возникают из-за того, что программисты не расследуют много о том, что требуется удаленному API для подключения или аутентификации.

Например, PHP пересылает файлы cookie из заголовков HTTP автоматически, но при использовании пакета "node" он должен быть явно установлен (например, пакетом "soap-cookie" )...

Ответ 9

Я использовал сетевой модуль node, чтобы открыть сокет для веб-службы.

/* 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 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;
    }

Открой мыльный отклик, я использовал модуль - xml2js

var parser = new xml2js.Parser({
    normalize: true,
    trim: true,
    explicitArray: false
});
//client.net.setEncoding('utf8');

client.net.on('data', function(response) {
    parser.parseString(response);
});

parser.addListener('end', function( xmlResponse ) {
    var response = xmlResponse['env:Envelope']['env:Header']['n:Response']._;
    /* handle Login response */
    if (response == 'Login'){
        /* make SOAP LoginContinue request */
        soapGps(xmlResponse, client, '');
    }
    /* handle LoginContinue response */
    if (response == 'LoginContinue') {
        if(xmlResponse['env:Envelope']['env:Body']['n:ResponseLoginContinue']['n:ErrCode'] == "ok") {           
            var nTimeMsecServer = xmlResponse['env:Envelope']['env:Body']['n:ResponseLoginContinue']['n:CurrentTime'];
            var nTimeMsecOur = new Date().getTime();
        } else {
            /* Unsuccessful login */
            io.to(client.id).emit('Error', "invalid login");
            client.net.destroy();
        }
    }
});

Надеюсь, что это поможет кому-то

Ответ 10

Добавление в решение Kim.J: вы можете добавить preserveWhitespace=true, чтобы избежать ошибки пробела. Как это:

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

Ответ 11

Вы также можете использовать wsdlrdr. EasySoap в основном переписывает wsdlrdr с некоторыми дополнительными методами. Будьте осторожны, у easysoap нет метода getNamespace, доступного на wsdlrdr.

Ответ 12

Для тех, кто SOAP с SOAP и хочет получить краткое объяснение и руководство, я настоятельно рекомендую эту замечательную среднюю статью.

Вы также можете использовать пакет node-soap с этим простым руководством.