向Node js中的休息服务发送https请求的步骤
将节点js中的https请求发送到休息服务的步骤是什么? 我有一个暴露像https://133-70-97-54-43.sample.com/feedSample/Query_Status_View/Query_Status/Output1?STATUS=Joined%20school
如何传递请求以及我需要为这个API提供哪些选项,例如主机,端口,路径和方法?
最简单的方法是使用请求模块。
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('datan');
req.write('datan');
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); } );
链接地址: http://www.djcxy.com/p/41085.html
上一篇: Steps to send a https request to a rest service in Node js