js实现soap
SOAP 请求的基本概念
SOAP(Simple Object Access Protocol)是一种基于 XML 的协议,用于在 Web 服务之间交换结构化信息。在 JavaScript 中实现 SOAP 请求通常需要构造符合 SOAP 规范的 XML 请求体,并通过 HTTP 发送到目标服务端点。

使用 XMLHttpRequest 发送 SOAP 请求
以下是使用原生 JavaScript 的 XMLHttpRequest 发送 SOAP 请求的示例代码:

const soapRequest = `
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:web="http://www.example.com/webservice">
<soapenv:Header/>
<soapenv:Body>
<web:GetData>
<web:InputParameter>value</web:InputParameter>
</web:GetData>
</soapenv:Body>
</soapenv:Envelope>
`;
const xhr = new XMLHttpRequest();
xhr.open('POST', 'https://example.com/soap-endpoint', true);
xhr.setRequestHeader('Content-Type', 'text/xml;charset=UTF-8');
xhr.setRequestHeader('SOAPAction', 'http://www.example.com/webservice/GetData');
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
console.log(xhr.responseXML);
} else {
console.error('Error:', xhr.statusText);
}
}
};
xhr.send(soapRequest);
使用 Fetch API 发送 SOAP 请求
现代 JavaScript 可以使用 fetch API 发送 SOAP 请求,代码更简洁:
const soapRequest = `
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:web="http://www.example.com/webservice">
<soapenv:Header/>
<soapenv:Body>
<web:GetData>
<web:InputParameter>value</web:InputParameter>
</web:GetData>
</soapenv:Body>
</soapenv:Envelope>
`;
fetch('https://example.com/soap-endpoint', {
method: 'POST',
headers: {
'Content-Type': 'text/xml;charset=UTF-8',
'SOAPAction': 'http://www.example.com/webservice/GetData'
},
body: soapRequest
})
.then(response => response.text())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
使用第三方库简化 SOAP 请求
对于复杂的 SOAP 交互,可以使用第三方库如 soap(Node.js)或 axios(浏览器/Node.js)。以下是使用 soap 库的示例(Node.js 环境):
const soap = require('soap');
const url = 'https://example.com/soap-endpoint?wsdl';
const args = { InputParameter: 'value' };
soap.createClient(url, (err, client) => {
if (err) throw err;
client.GetData(args, (err, result) => {
if (err) throw err;
console.log(result);
});
});
注意事项
- SOAP Action 头:某些服务要求
SOAPAction头必须与 WSDL 中定义的操作匹配。 - XML 命名空间:确保 XML 命名空间(如
soapenv、web)与服务端定义的完全一致。 - CORS 问题:在浏览器中发送跨域 SOAP 请求时,需确保服务端支持 CORS 或通过代理解决。
- 错误处理:SOAP 错误通常以 XML 格式返回,需解析响应内容以获取详细信息。
通过以上方法,可以在 JavaScript 中实现 SOAP 请求的发送与响应处理。






