Recently developing a rest-based API interface in the product, combined with your recent research on node. JS, would like to develop a rest client for testing purposes based on it.
With the initial research, node. JS is very handy to develop HTTP client.
Reasons to choose node:
1. It's very convenient to test JSON-formatted data using a fully JavaScript-based node
2. Node has a good community support. (GitHub is now the largest open source community for JavaScript)
by Example:
| 1234567891011121314151617181920212223242526272829303132333435363738 |
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(); |
Save the above code as resttest.js and run it on the command line: node Resttest.js can see the results of the output.
The code above simply uses the node's own assert to do unit test and, if interested, introduces a test framework for BDD such as Jasmine. (To be Continued ...) )
"Nodejs" uses node. js to implement rest client invoke rest API