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

zvms9eto  于 2023-02-15  发布在  Node.js
关注(0)|答案(6)|浏览(127)

在node js中向rest服务发送https请求的步骤是什么?我公开了一个类似(Original link not working...)的API
如何传递请求,我需要为这个API给予哪些选项,如主机、端口、路径和方法?

pieyvz9o

pieyvz9o1#

只需使用核心https模块和https.request函数,例如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();
wz3gfoph

wz3gfoph2#

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

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

j2cgzkjk3#

注意如果你使用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();
z6psavjg

z6psavjg4#

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

// 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); }  );
aurhwmvo

aurhwmvo5#

由于没有任何关于"GET“方法的例子,这里有一个,问题是为了正确发送请求,选项Object中的path应该设置为'/'

const https = require('https')
const options = {
  hostname: 'www.google.com',
  port: 443,
  path: '/',
  method: 'GET',
  headers: {
    'Accept': 'plain/html',
    'Accept-Encoding': '*',
  }
}

const req = https.request(options, res => {
  console.log(`statusCode: ${res.statusCode}`);
  console.log('headers:', res.headers);

  res.on('data', d => {
    process.stdout.write(d)
  })
})

req.on('error', error => {
  console.error(`Error on Get Request --> ${error}`)
})

req.end()
pnwntuvh

pnwntuvh6#

使用'GET'方法的示例很好,但它也可以在TypeScript/Node.js设置中与常量变量一起使用。如果是这种情况,则必须在https.request函数之外定义('error ')和end()上的函数。

const https = require('https')
const options = {
  hostname: 'www.google.com',
  port: 443,
  path: '/',
  method: 'GET',
  headers: {
    'Accept': 'plain/html',
    'Accept-Encoding': '*',
  }
}

const request = https.request(options, res => {
  const callback = (data: string) => {
    process.stdout.write(`response data: ${data}`);
  }
  res.on('data', callback)
})

request.on('error', error => {
  console.error(`Error on Get Request --> ${error}`)
})
request.end()

相关问题