ノードjsでhttpsリクエストを残りのサービスに送信する手順は何ですか? 私は(元のリンクが機能していない...)のように公開されたAPIを持っています
リクエストを渡す方法と、ホスト、ポート、パス、メソッドなど、この API に指定する必要があるオプションは何ですか?
ノードjsでhttpsリクエストを残りのサービスに送信する手順は何ですか? 私は(元のリンクが機能していない...)のように公開されたAPIを持っています
リクエストを渡す方法と、ホスト、ポート、パス、メソッドなど、この API に指定する必要があるオプションは何ですか?
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();
最も簡単な方法は、リクエストモジュールを使用することです。
request('https://example.com/url?a=b', function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body);
}
});
を使用している場合はhttps.request
、 の本体を直接使用しないで くださいres.on('data',..
。大きなデータがチャンクで入ってくる場合、これは失敗します。したがって、すべてのデータを連結してから、 で応答を処理する必要がありますres.on('end'
。例 -
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();
リクエストモジュールを使用すると問題が解決しました。
// 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); } );