46

ノードjsでhttpsリクエストを残りのサービスに送信する手順は何ですか? 私は(元のリンクが機能していない...)のように公開されたAPIを持っています

リクエストを渡す方法と、ホスト、ポート、パス、メソッドなど、この API に指定する必要があるオプションは何ですか?

4

5 に答える 5

70

https.request関数でコアhttpsモジュールを使用するだけです。リクエストの例(似ています):POSTGET

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();
于 2012-10-29T18:52:13.407 に答える
30

最も簡単な方法は、リクエストモジュールを使用することです。

request('https://example.com/url?a=b', function (error, response, body) {
  if (!error && response.statusCode == 200) {
    console.log(body);
  }
});
于 2012-10-29T14:31:34.207 に答える
21

を使用している場合は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();
于 2018-08-10T09:42:02.467 に答える
5

リクエストモジュールを使用すると問題が解決しました。

// 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); }  );         
于 2012-10-30T06:24:03.013 に答える