Steps to send a https request to a rest service in Node js
将节点js中的https请求发送到休息服务的步骤是什么?
我有一个api暴露像https://133-70-97-54-43.sample.com/feedSample/Query_Status_View/Query_Status/Output1?STATUS=Joined%20school
如何传递请求以及我需要为此API提供哪些选项
主机,端口,路径和方法?
只需将核心https模块与https.request函数一起使用即可。
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 | 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 '); req.write('data '); req.end(); |
最简单的方法是使用请求模块。
1 2 3 4 5 | request('https://example.com/url?a=b', function (error, response, body) { if (!error && response.statusCode == 200) { console.log(body); } }); |
请注意,如果您使用
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 39 40 | var options = { hostname:"www.google.com", port: 443, path:"/upload", method: 'POST', headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(post_data) } }; //change to http for local testing var req = https.request(options, function (res) { res.setEncoding('utf8'); var body = ''; res.on('data', function (chunk) { body = body + chunk; }); res.on('end',function(){ console.log("Body :" + body); if (res.statusCode != 200) { callback("Api call failed with response code" + res.statusCode); } else { callback(null); } }); }); req.on('error', function (e) { console.log("Error" :" + e.message); callback(e); }); // write data to request body req.write(post_data); req.end(); |
使用请求模块解决了问题。
1 2 3 4 5 6 7 8 9 10 11 12 13 | // 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模块来建立一个这样的请求:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | 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); } }); |