Javascript를 사용하는 가장 간단한 SOAP 예는 무엇입니까?
가능한 한 유용하게 사용하기 위해서는 다음과 같이 답해야 한다.
이것은 내가 만들 수 있는 가장 간단한 자바스크립트 SOAP 클라이언트이다.
<html>
<head>
<title>SOAP JavaScript Client Test</title>
<script type="text/javascript">
function soap() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open('POST', 'https://somesoapurl.com/', true);
// build SOAP request
var sr =
'<?xml version="1.0" encoding="utf-8"?>' +
'<soapenv:Envelope ' +
'xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ' +
'xmlns:api="http://127.0.0.1/Integrics/Enswitch/API" ' +
'xmlns:xsd="http://www.w3.org/2001/XMLSchema" ' +
'xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">' +
'<soapenv:Body>' +
'<api:some_api_call soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">' +
'<username xsi:type="xsd:string">login_username</username>' +
'<password xsi:type="xsd:string">password</password>' +
'</api:some_api_call>' +
'</soapenv:Body>' +
'</soapenv:Envelope>';
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
alert(xmlhttp.responseText);
// alert('done. use firebug/console to see network response');
}
}
}
// Send the POST request
xmlhttp.setRequestHeader('Content-Type', 'text/xml');
xmlhttp.send(sr);
// send request
// ...
}
</script>
</head>
<body>
<form name="Demo" action="" method="post">
<div>
<input type="button" value="Soap" onclick="soap();" />
</div>
</form>
</body>
</html> <!-- typo -->
브라우저가 XMLHtpRequest를 처리하는 방식에는 많은 변덕이 있으며, 이 JS 코드는 모든 브라우저에서 작동합니다.
https://github.com/ilinsky/xmlhttprequest
이 JS 코드는 XML을 사용하기 쉬운 자바스크립트 개체로 변환합니다.
http://www.terracoder.com/index.php/xml-objectifier
위의 JS 코드를 페이지에 포함시켜 외부 라이브러리 요구 사항을 충족할 수 있습니다.
var symbol = "MSFT";
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", "http://www.webservicex.net/stockquote.asmx?op=GetQuote",true);
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState == 4) {
alert(xmlhttp.responseText);
// http://www.terracoder.com convert XML to JSON
var json = XMLObjectifier.xmlToJSON(xmlhttp.responseXML);
var result = json.Body[0].GetQuoteResponse[0].GetQuoteResult[0].Text;
// Result text is escaped XML string, convert string to XML object then convert to JSON object
json = XMLObjectifier.xmlToJSON(XMLObjectifier.textToXML(result));
alert(symbol + ' Stock Quote: $' + json.Stock[0].Last[0].Text);
}
}
xmlhttp.setRequestHeader("SOAPAction", "http://www.webserviceX.NET/GetQuote");
xmlhttp.setRequestHeader("Content-Type", "text/xml");
var xml = '<?xml version="1.0" encoding="utf-8"?>' +
'<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ' +
'xmlns:xsd="http://www.w3.org/2001/XMLSchema" ' +
'xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">' +
'<soap:Body> ' +
'<GetQuote xmlns="http://www.webserviceX.NET/"> ' +
'<symbol>' + symbol + '</symbol> ' +
'</GetQuote> ' +
'</soap:Body> ' +
'</soap:Envelope>';
xmlhttp.send(xml);
// ...Include Google and Terracoder JS code here...
다른 두 가지 옵션:
자바스크립트 SOAP 클라이언트:
http://www.guru4.net/articoli/javascript-soap-client/en/
WSDL에서 자바스크립트 생성:
https://cwiki.apache.org/confluence/display/CXF20DOC/WSDL+to+Javascript
<수정>웹 서비스가 페이지와 동일한 도메인에 있지 않은 경우 이 작업을 직접 JavaScript에서 수행할 수 없습니다.</스트라이크> 편집: 2008년 및 IE<10에서는 서비스가 귀하의 페이지와 동일한 도메인에 있지 않는 한 직접 javascript로 수행할 수 없습니다.
웹 서비스가 다른 도메인에 있는 경우(그리고 IE<10을 지원해야 함) 결과를 검색하여 반환하는 사용자 도메인의 프록시 페이지를 사용해야 합니다. 이전 IE 지원이 필요하지 않다면 서비스에 CORS 지원을 추가해야 합니다. 두 경우 모두 결과를 직접 구문 분석할 필요가 없기 때문에 timyates가 제안한 lib와 같은 것을 사용해야 합니다.
웹 서비스가 자신의 도메인에 있다면 SOAP를 사용하지 마십시오. 그렇게 해야 할 합당한 이유가 없습니다. 만약 웹 서비스가 당신의 도메인에 있다면, 그것을 수정하여 JSON을 반환하고 SOAP와 함께 오는 모든 번거로움을 당신 스스로 해결할 수 있도록 하세요.
간단한 대답은: javascript에서 SOAP 요청을 하지 마세요. 웹 서비스를 사용하여 다른 도메인에서 데이터를 요청하면 서버 측에서 결과를 구문 분석하여 js 친화적인 형식으로 반환합니다.
jquery.soap 플러그인을 사용하여 작업을 대신 수행할 수 있습니다.
이 스크립트는 $.ajax를 사용하여 SOAPenvelope를 보냅니다. XML DOM, XML 문자열 또는 JSON을 입력으로 사용할 수 있으며 응답도 XML DOM, XML 문자열 또는 JSON으로 반환할 수 있습니다.
사이트의 사용 예:
$.soap({
url: 'http://my.server.com/soapservices/',
method: 'helloWorld',
data: {
name: 'Remy Blom',
msg: 'Hi!'
},
success: function (soapResponse) {
// do stuff with soapResponse
// if you want to have the response as JSON use soapResponse.toJSON();
// or soapResponse.toString() to get XML string
// or soapResponse.toXML() to get XML DOM
},
error: function (SOAPResponse) {
// show error
}
});
이거 먹어본 사람 있어? https://github.com/doedje/jquery.soap
구현이 매우 쉬워 보입니다.
예:
$.soap({
url: 'http://my.server.com/soapservices/',
method: 'helloWorld',
data: {
name: 'Remy Blom',
msg: 'Hi!'
},
success: function (soapResponse) {
// do stuff with soapResponse
// if you want to have the response as JSON use soapResponse.toJSON();
// or soapResponse.toString() to get XML string
// or soapResponse.toXML() to get XML DOM
},
error: function (SOAPResponse) {
// show error
}
});
을 초래하게 될 것이다
<soap:Envelope
xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<helloWorld>
<name>Remy Blom</name>
<msg>Hi!</msg>
</helloWorld>
</soap:Body>
</soap:Envelope>
토마스:
JSON은 javascript이기 때문에 프런트 엔드용으로 선호됩니다. 따라서 처리할 XML이 없습니다. 이것 때문에 SOAP는 도서관을 사용하지 않는 것이 골칫거리입니다. 누군가가 좋은 도서관인 SOAPClient를 언급해서, 우리는 우리의 프로젝트를 위해 그것을 시작했습니다. 하지만 한계가 있어 많은 부분을 다시 작성해야 했다. 이것은 SOAPjs로 출시되었으며 서버에 복잡한 객체를 전달하는 것을 지원하며 다른 도메인에서 서비스를 소비하기 위한 일부 샘플 프록시 코드를 포함한다.
<html>
<head>
<title>Calling Web Service from jQuery</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#btnCallWebService").click(function (event) {
var wsUrl = "http://abc.com/services/soap/server1.php";
var soapRequest ='<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> <soap:Body> <getQuote xmlns:impl="http://abc.com/services/soap/server1.php"> <symbol>' + $("#txtName").val() + '</symbol> </getQuote> </soap:Body></soap:Envelope>';
alert(soapRequest)
$.ajax({
type: "POST",
url: wsUrl,
contentType: "text/xml",
dataType: "xml",
data: soapRequest,
success: processSuccess,
error: processError
});
});
});
function processSuccess(data, status, req) { alert('success');
if (status == "success")
$("#response").text($(req.responseXML).find("Result").text());
alert(req.responseXML);
}
function processError(data, status, req) {
alert('err'+data.state);
//alert(req.responseText + " " + status);
}
</script>
</head>
<body>
<h3>
Calling Web Services with jQuery/AJAX
</h3>
Enter your name:
<input id="txtName" type="text" />
<input id="btnCallWebService" value="Call web service" type="button" />
<div id="response" ></div>
</body>
</html>
예를 들어 SOAP 튜토리얼이 포함된 Hear가 가장 좋습니다.
http://www.codeproject.com/Articles/12816/JavaScript-SOAP-Client
JavaScript로 SOAP 웹 서비스를 쉽게 소비 -> 듣기 B
function fncAddTwoIntegers(a, b)
{
varoXmlHttp = new XMLHttpRequest();
oXmlHttp.open("POST",
"http://localhost/Develop.NET/Home.Develop.WebServices/SimpleService.asmx'",
false);
oXmlHttp.setRequestHeader("Content-Type", "text/xml");
oXmlHttp.setRequestHeader("SOAPAction", "http://tempuri.org/AddTwoIntegers");
oXmlHttp.send(" \
<soap:Envelope xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' \
xmlns:xsd='http://www.w3.org/2001/XMLSchema' \
xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'> \
<soap:Body> \
<AddTwoIntegers xmlns='http://tempuri.org/'> \
<IntegerOne>" + a + "</IntegerOne> \
<IntegerTwo>" + b + "</IntegerTwo> \
</AddTwoIntegers> \
</soap:Body> \
</soap:Envelope> \
");
return oXmlHttp.responseXML.selectSingleNode("//AddTwoIntegersResult").text;
}
이것이 모든 요구 사항을 충족시키지는 못할 수 있지만 실제로 질문에 대답하기 위한 시작입니다. ActiveXObject("MSXML2.XMLHTTP")에 대해 XMLHtpRequest()를 전환했습니다.
몇 가지 좋은 예(및 이미 만들어진 자바스크립트 SOAP 클라이언트!) 여기 있습니다. http://plugins.jquery.com/soap/
readme를 확인하고 동일한 출처의 브라우저 제한에 주의하십시오.
가장 간단한 예는 다음과 같다.
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<GetInfoByZIP xmlns="http://www.webserviceX.NET">
<USZip>string</USZip>
</GetInfoByZIP>
</soap:Body>
</soap:Envelope>
<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>
<GetInfoByZIPResponse xmlns="http://www.webserviceX.NET">
<GetInfoByZIPResult>
<NewDataSet xmlns="">
<Table>
<CITY>...</CITY>
<STATE>...</STATE>
<ZIP>...</ZIP>
<AREA_CODE>...</AREA_CODE>
<TIME_ZONE>...</TIME_ZONE>
</Table>
</NewDataSet>
</GetInfoByZIPResult>
</GetInfoByZIPResponse>
</soap:Body>
</soap:Envelope>
하지만 외부 자바스크립트 라이브러리가 없으면 번거롭습니다.
function SoapQuery(){
var namespace = "http://tempuri.org/";
var site = "http://server.com/Service.asmx";
var xmlhttp = new ActiveXObject("Msxml2.ServerXMLHTTP.6.0");
xmlhttp.setOption(2, 13056 ); /* if use standard proxy */
var args,fname = arguments.callee.caller.toString().match(/ ([^\(]+)/)[1]; /*Имя вызвавшей ф-ции*/
try { args = arguments.callee.caller.arguments.callee.toString().match(/\(([^\)]+)/)[1].split(",");
} catch (e) { args = Array();};
xmlhttp.open('POST',site,true);
var i, ret = "", q = '<?xml version="1.0" encoding="utf-8"?>'+
'<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">'+
'<soap:Body><'+fname+ ' xmlns="'+namespace+'">';
for (i=0;i<args.length;i++) q += "<" + args[i] + ">" + arguments.callee.caller.arguments[i] + "</" + args[i] + ">";
q += '</'+fname+'></soap:Body></soap:Envelope>';
// Send the POST request
xmlhttp.setRequestHeader("MessageType","CALL");
xmlhttp.setRequestHeader("SOAPAction",namespace + fname);
xmlhttp.setRequestHeader('Content-Type', 'text/xml');
//WScript.Echo("Запрос XML:" + q);
xmlhttp.send(q);
if (xmlhttp.waitForResponse(5000)) ret = xmlhttp.responseText;
return ret;
};
function GetForm(prefix,post_vars){return SoapQuery();};
function SendOrder2(guid,order,fio,phone,mail){return SoapQuery();};
function SendOrder(guid,post_vars){return SoapQuery();};
XMLHtpRequest에 기반한 Angularjs $http 래핑 기준. 헤더 내용 집합에서 다음 코드만 사용할 수 있습니다.
"Content-Type": "text/xml; charset=utf-8"
예를 들어:
function callSoap(){
var url = "http://www.webservicex.com/stockquote.asmx";
var soapXml = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:web=\"http://www.webserviceX.NET/\"> "+
"<soapenv:Header/> "+
"<soapenv:Body> "+
"<web:GetQuote> "+
"<web:symbol></web:symbol> "+
"</web:GetQuote> "+
"</soapenv:Body> "+
"</soapenv:Envelope> ";
return $http({
url: url,
method: "POST",
data: soapXml,
headers: {
"Content-Type": "text/xml; charset=utf-8"
}
})
.then(callSoapComplete)
.catch(function(message){
return message;
});
function callSoapComplete(data, status, headers, config) {
// Convert to JSON Ojbect from xml
// var x2js = new X2JS();
// var str2json = x2js.xml_str2json(data.data);
// return str2json;
return data.data;
}
}
질문은 'Javascript를 사용한 가장 간단한 SOAP 예는 무엇인가?'입니다.
이 답변은 브라우저가 아닌 Node.js 환경의 예입니다. (스크립트 soap-node.js의 이름을 붙이자) 그리고 우리는 기사의 참조 목록을 얻기 위한 예로 유럽 PMC의 공용 SOAP 웹 서비스를 사용할 것이다.
const XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
const DOMParser = require('xmldom').DOMParser;
function parseXml(text) {
let parser = new DOMParser();
let xmlDoc = parser.parseFromString(text, "text/xml");
Array.from(xmlDoc.getElementsByTagName("reference")).forEach(function (item) {
console.log('Title: ', item.childNodes[3].childNodes[0].nodeValue);
});
}
function soapRequest(url, payload) {
let xmlhttp = new XMLHttpRequest();
xmlhttp.open('POST', url, true);
// build SOAP request
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
parseXml(xmlhttp.responseText);
}
}
}
// Send the POST request
xmlhttp.setRequestHeader('Content-Type', 'text/xml');
xmlhttp.send(payload);
}
soapRequest('https://www.ebi.ac.uk/europepmc/webservices/soap',
`<?xml version="1.0" encoding="UTF-8"?>
<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
<S:Header />
<S:Body>
<ns4:getReferences xmlns:ns4="http://webservice.cdb.ebi.ac.uk/"
xmlns:ns2="http://www.scholix.org"
xmlns:ns3="https://www.europepmc.org/data">
<id>C7886</id>
<source>CTX</source>
<offSet>0</offSet>
<pageSize>25</pageSize>
<email>[email protected]</email>
</ns4:getReferences>
</S:Body>
</S:Envelope>`);
코드를 실행하기 전에 다음 두 가지 패키지를 설치해야 합니다.
npm install xmlhttprequest
npm install xmldom
이제 코드를 실행할 수 있습니다.
node soap-node.js
출력은 다음과 같습니다.
Title: Perspective: Sustaining the big-data ecosystem.
Title: Making proteomics data accessible and reusable: current state of proteomics databases and repositories.
Title: ProteomeXchange provides globally coordinated proteomics data submission and dissemination.
Title: Toward effective software solutions for big biology.
Title: The NIH Big Data to Knowledge (BD2K) initiative.
Title: Database resources of the National Center for Biotechnology Information.
Title: Europe PMC: a full-text literature database for the life sciences and platform for innovation.
Title: Bio-ontologies-fast and furious.
Title: BioPortal: ontologies and integrated data resources at the click of a mouse.
Title: PubMed related articles: a probabilistic topic-based model for content similarity.
Title: High-Impact Articles-Citations, Downloads, and Altmetric Score.