首页 > 解决方案 > 在 JavaScript 中创建 SOAP XMLHttpRequest 请求

问题描述

我正在尝试在 JavaScript 中创建一个 SOAP 请求,但我得到了错误的响应。

这是我的要求:

callSOAP() {
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.open('POST', 'https://webapi.allegro.pl/service.php', true);
    var sr = 
    '<?xml version="1.0" encoding="utf-8"?>' +
    '<SOAP-ENV:Envelope ' + 
        'xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" ' + 
        'xmlns:main="https://webapi.allegro.pl/service.php" ' +
        'xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ' +
        'xmlns:xsd="http://www.w3.org/2001/XMLSchema">' +
        '<SOAP-ENV:Body>' +
            '<main:DoGetCountriesRequest>' +
                '<main:countryCode>1</main:countryCode>' +
                '<main:webapiKey>xxxxxxxx</main:webapiKey>' +
            '</main:DoGetCountriesRequest>' +
        '</SOAP-ENV:Body>' +
    '</SOAP-ENV:Envelope>';

    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            console.log(xmlhttp.response);
        }
    };
    xmlhttp.setRequestHeader('Content-Type', 'text/xml');
    xmlhttp.send(sr);
}

我尝试调用“DoGetCountriesRequest”方法,但响应是状态代码 500,并带有消息“无效 XML”。

这是在 JavaScript 中调用 SOAP 方法的正确方法吗?我的请求有什么问题?

标签: javascriptsoapxmlhttprequest

解决方案


看起来您正在将请求发送到?wsdl端点 - 从您的xmlhttp.open()方法调用中的 URL 中删除它以将其发送到服务本身。

似乎您的 SOAP 消息格式不正确-您SOAP-ENV:Envelope过早地关闭了开始标记-它还需要围绕您的xmlns:xsixmlns:xsd命名空间定义:

'<?xml version="1.0" encoding="utf-8"?>' +
    '<SOAP-ENV:Envelope ' + 
        'xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:main="https://webapi.allegro.pl/service.php"' +
        'xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ' +
        'xmlns:xsd="http://www.w3.org/2001/XMLSchema">' + ...

后续编辑: 您的 countryCode 和 webapiKey 开始标记中有一些双引号需要删除,看起来消息本身不符合 WSDL - WSDL 中的操作doGetCountries需要一个DoGetCountriesRequest对象。尝试类似:

var sr = 
    '<?xml version="1.0" encoding="utf-8"?>' +
    '<SOAP-ENV:Envelope ' + 
        'xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" ' + 
        'xmlns:main="https://webapi.allegro.pl/service.php" ' +
        'xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ' +
        'xmlns:xsd="http://www.w3.org/2001/XMLSchema">' +
        '<SOAP-ENV:Body>' +
            '<main:DoGetCountriesRequest>' +
                '<main:countryCode>1</main:countryCode>' +
                '<main:webapiKey>xxxxxxxx</main:webapiKey>' +
            '</main:DoGetCountriesRequest>' +
        '</SOAP-ENV:Body>' +
    '</SOAP-ENV:Envelope>';

推荐阅读