向Node js中的rest服务发送https请求的步骤

在节点js发送https请求到rest服务的步骤是什么? 我有一个暴露像https://133-70-97-54-43.sample.com/feedSample/Query_Status_View/Query_Status/Output1?STATUS=Joined%20school

如何传递请求,我需要给这个API,如主机,端口,path和方法有什么select?

最简单的方法是使用请求模块。

request('https://example.com/url?a=b', function (error, response, body) { if (!error && response.statusCode == 200) { console.log(body); } }); 

只需使用https.request函数的核心https模块即可 。 POST请求示例( GET将类似):

 var https = require('https'); var options = { host: 'www.google.com', port: 443, path: '/upload', method: 'POST' }; var req = https.request(options, function(res) { console.log('STATUS: ' + res.statusCode); console.log('HEADERS: ' + JSON.stringify(res.headers)); res.setEncoding('utf8'); res.on('data', function (chunk) { console.log('BODY: ' + chunk); }); }); req.on('error', function(e) { console.log('problem with request: ' + e.message); }); // write data to request body req.write('data\n'); req.write('data\n'); req.end(); 

使用请求模块解决了问题。

 // Include the request library for Node.js var request = require('request'); // Basic Authentication credentials var username = "vinod"; var password = "12345"; var authenticationHeader = "Basic " + new Buffer(username + ":" + password).toString("base64"); request( { url : "https://133-70-97-54-43.sample.com/feedSample/Query_Status_View/Query_Status/Output1?STATUS=Joined%20school", headers : { "Authorization" : authenticationHeader } }, function (error, response, body) { console.log(body); } ); 

你可以使用superagent和node的url模块来build立一个这样的请求:

 var request = require('superagent'); var url = require('url'); var urlObj = { protocol: 'https', host: '133-70-97-54-43.sample.com', pathname: '/feedSample/Query_Status_View/Query_Status/Output1' }; request .get(url.format(urlObj)) .query({'STATUS': 'Joined school'}) .end(function(res) { if (res.ok) { console.log(res.body); } });