打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
【nodejs】使用Node.js实现REST Client调用REST API

最近在产品中开发基于REST的API接口,结合自己最近对Node.js的研究,想基于它开发一个REST Client做测试之用。

通过初步研究,Node.js开发HTTP Client还是挺方便的。

 

选用Node的理由:

1. 使用完全基于JavaScript的Node测试JSON格式的数据,非常之方便

2. Node有很好的社区支持。(现在GitHub上已成了JavaScript最大的开源社区)

 

By Example:

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的测试框架。(待续。。。)

 

生成测报告:

1. Maven Jasmine plugin (SM Client Team已在使用了)

2. Testacular by Google(本博主推荐)

 

P.S.:

如果你是CoffeeScript的Fans可以参考下面的代码片段

http = require 'http'equal = require('assert').equalusername = 'falcon'password = ''_auth = 'Basic ' + new Buffer(username + ':' + password).toString('base64')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'req = http.request options, (res) ->     console.log('STATUS: ' + res.statusCode)    equal(200, res.statusCode)    console.log('HEADERS: ' + JSON.stringify(res.headers))    res.on 'data', (chunk)->          console.log('BODY: ' + chunk)    req.on 'error', (e)->      console.log('problem with request: ' + e.message)req.end()

 

 

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
NodeJS 常用模块推荐
基于NodeJs的Redis使用
NodeJS服务总是崩溃的解决办法 错误日志输出
Nodejs 入门学习
跟我学Nodejs(三)
开发笔记:基于Electon的图片采集工具
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服