【nodejs】使用Node.js實現REST Client調用REST API

 

最近在產品中開發基於REST的API接口,結合本身最近對Node.js的研究,想基於它開發一個REST Client作測試之用。javascript

經過初步研究,Node.js開發HTTP Client仍是挺方便的。java

 

選用Node的理由:node

1. 使用徹底基於JavaScript的Node測試JSON格式的數據,很是之方便git

2. Node有很好的社區支持。(如今GitHub上已成了JavaScript最大的開源社區)github

 

By Example:app

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
var http = require( 'http' );
var equal = require( 'assert' ).equal;
 
var username = 'falcon' ;
var password = '' ;
var _auth = 'Basic ' + new Buffer(username + ':' + password).toString( 'base64' )
 
var options = {
     host: 'localhost' ,
     port: 13080,
     path: '/SM/7/rest/1.1/incident_list/' ,
     method: 'GET' ,
     headers:{
         'accept' : '*/*' ,
         'content-type' : "application/atom+xml" ,
         'accept-encoding' : 'gzip, deflate' ,
         'accept-language' : 'en-US,en;q=0.9' ,
         'authorization' : _auth,
         'user-agent' : 'nodejs rest client'
     }
};
 
var req = http.request(options, function (res) {
     console.log( 'STATUS: ' + res.statusCode);
     equal(200, res.statusCode);
     console.log( 'HEADERS: ' + JSON.stringify(res.headers));
 
     res.on( 'data' , function (chunk) {
          console.log( 'BODY: ' + chunk);
     });
});
 
req.on( 'error' , function (e) {
   console.log( 'problem with request: ' + e.message);
});
 
 
req.end();

 

將上述代碼保存成RestTest.js,而後在命令行上運行: node RestTest.js 就能夠看輸出的結果了。框架

 

上面的代碼只是使用Node自帶的Assert作Unit Test,若是有興趣的話,仍是引入Jasmine等BDD的測試框架。(待續。。。)ide

相關文章
相關標籤/搜索