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

Posted

技术标签:

【中文标题】Node js中向rest服务发送https请求的步骤【英文标题】:Steps to send a https request to a rest service in Node js 【发布时间】:2012-10-18 18:21:57 【问题描述】:

在 node js 中将 https 请求发送到 rest 服务的步骤是什么? 我有一个公开的 api,例如 (Original link not working...)

如何传递请求以及我需要为此 API 提供哪些选项,例如 主机、端口、路径和方法?

【问题讨论】:

在下面所有的回复中很有趣,你是唯一正确回答他答案的人。 【参考方案1】:

只需将核心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();

【讨论】:

编辑了上面的 - 问题是关于 https (!) - 我们需要 var https = require('https'); 我也是这样做的,但是遇到了套接字挂断错误。似乎 TLS 失败了。 并且请求模块会抛出相同的错误,并且当我使用 SSLv3_methods 时出现 SSLv3 disabled 错误。我真的很高兴用 nodejs 发送一个普通的 ssl/tls 请求。 能否请您提一下如何发送帖子数据【参考方案2】:

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

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

【讨论】:

嗨 zeMirco,乔希,大卫。谢谢大家。我得到了如下解决方案。它类似于乔希。 如果我们想将 body 传递给另一个函数,我们该怎么做呢?请澄清。 更新:requesthas been deprecated,Aniket 的回答是截至 2020 年 5 月的最佳回答 @invider:我不同意。首先,“弃用”并不完全准确。更好的描述是“完成”。 request 不会添加新功能,但会修复错误。应考虑这是否适合特定项目。其次,您建议的答案使用核心 http,我不会说这是“最佳”选项。核心 http 相对原始,缺少许多您最终会自己实现的功能。我建议大多数人最好使用支持良好的高级 http 模块之一。 @josh3736 根据文档和前进的路径,它已被弃用。 * 请求将停止接受新功能。 * 请求将停止考虑重大更改。【参考方案3】:

请注意,如果您使用的是 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();

【讨论】:

有什么办法可以像https.request(url, options, function (res) )一样使用https。在我的情况下,我会从映射中获取 url,否则我必须中断并再次加入 url 来完成工作。 @ChitrankDixit 我不完全了解您的用例,但您可以做到。看看nodejs.org/api/https.html#https_https_request_options_callback。你可以https.request(url[, options][, callback])【参考方案4】:

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

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

【讨论】:

【参考方案5】:

由于没有任何使用“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()

【讨论】:

以上是关于Node js中向rest服务发送https请求的步骤的主要内容,如果未能解决你的问题,请参考以下文章

如何从 Angular 6 向 node.js 发送 https 请求

如何在 Node.JS 中向 sequelize.js 添加自定义函数?

Node.js 通过 REST API 发送图像

当您不知道页数时,如何使用 Node.js 在 while 循环中向 API 发出多个分页 GET 请求?

编写 Node.js Rest API 的 10 个最佳实践

Node.js https.post 请求 [重复]