node.js webservice

    由於項目需要,要了解和使用webservice服務,在網上查詢了一下,webservice的特點是實現跨平臺,但是我需要自己模擬一個服務器端和客戶端,各種找資料~~~~

    個人心得,不對勿噴--------------

    在node.js 中,webservice一下就能查到soap模塊,但我最終並沒有使用soap模塊,而是soap-server模塊構建服務器。soap中需要自行定義一個wsdl文件,其實這個文件就是定義該服務器提供哪些服務(方法),以及每個方法的輸入格式和輸出格式,我沒有使用這種方式,因此不羅嗦了。soap-server模塊構建服務器,方式很簡單,不需要自己定義wsdl文件,它會自動生成,模塊中有示例,此處不再舉例。webservice的實質其實就是http服務器,只不過它會在該http服務器上定義一個webservice的訪問路徑,不怎麼說的清楚,舉例:

  var soap = require('soap-server');
  function MyTestService(){
  
  }
  MyTestService.prototype.test1 = function(myArg1){
   	  return myArg1 + '123456';
  };
  var soapServer = new soap.SoapServer();
  var soapService = soapServer.addService('testService', new MyTestService());
  soapServer.listen(8888);
說明一下:此處是經過soap-server封裝過,但實質是http服務監聽了8888端口,webservice是接收 /testService 的訪問路徑,即當訪問爲:http://xxxx:8888/testService 時,服務會轉到webservice中,假如指定的方法是test1,那麼就會執行函數:
MyTestService.prototype.test1 = function(myArg1){
   	  return myArg1 + '123456';
  };


以上是服務端程序,現在來說說客戶端如何訪問,webservice服務在node中基本都是使用soap協議訪問,soap的實質是http和xml,path指定成webservice中的路徑,此處爲:/testService。和普通的http訪問方式不一樣的地方有兩項:

    1)headers中需要指定SOAPAction:函數名(需要訪問的函數名,此處爲test1)

    2)數據格式爲xml,並且是soap格式的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>'
	+ '<test1 xmlns="http://localhost:8888/">'
	+ '<myArg1>"Krime"</myArg1>'
	+ '</test1>'
	+ '</soap:Body>'
	+ '</soap:Envelope>';
然後按照普通的http訪問方式訪問即可,我測試是使用的POST方式。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章