SOAP API 调用使用者axios.post()
代替axios.get()
POST enctype 属性可以是 multipart/form-data 或 application/x-www-form-urlencoded,而对于 METHOD="GET",仅允许 application/x-www-form-urlencoded。
GET 仅发送 ASCII,当将它们以 ASCII 数据形式通过 URL 传递并作为 URL 的一部分发送时,无法以 XML 格式发送多行 TEXT。另一方面,二进制数据、图像等文件都可以通过body中的METHOD="POST"提交。
这就是为什么 POST 在 SOAP API 调用中常见而不是 GET。
const response = await axios.post(
url,
payload,
{
headers: {
'Content-Type': 'text/xml; charset=utf-8'
}
}
);
我将演示一个补充计算器 SOAP 服务 https://schemasxmlsoap.azurewebsites.net/soap/envelope/ : 计算器 http://www.dneonline.com/calculator.asmx
WSDL(Web 服务描述语言)描述了一个服务的功能
基于 SOAP 的 Web 服务。
完整代码
const axios = require("axios");
const jsdom = require("jsdom");
const getAdd = async (a, b) => {
const url = 'http://www.dneonline.com/calculator.asmx'
const payload =`<?xml version="1.0" encoding="utf-8"?> \
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> \
<soap:Body> \
<Add xmlns="http://tempuri.org/"> \
<intA>${a}</intA> \
<intB>${b}</intB> \
</Add> \
</soap:Body> \
</soap:Envelope>`
try {
const response = await axios.post(
url,
payload,
{
headers: {
'Content-Type': 'text/xml; charset=utf-8'
}
}
);
return Promise.resolve(response.data);
} catch (error) {
return Promise.reject(error);
}
};
getAdd(100,200)
.then(result => {
// display response of whole XML
console.log(result);
// extract addition result from XML
const dom = new jsdom.JSDOM(result);
console.log('100 + 200 = ' + dom.window.document.querySelector("AddResult").textContent); // 300
})
.catch(error => {
console.error(error);
});
安装库
npm install axios jsdom
运行程序
node add.js
Result
$ node add.js
<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://schemas.
xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance
" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body><AddResponse xmlns="ht
tp://tempuri.org/"><AddResult>300</AddResult></AddResponse></soap:Body></soap:En
velope>
100 + 200 = 300
参考GET 与 POST https://www.diffen.com/difference/GET-vs-POST-HTTP-Requests