"Nodejs" uses node. js to implement rest client invoke rest API

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.