NodeJS 中的 HTTPS 请求

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12851858/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 16:27:56  来源:igfitidea点击:

HTTPS request in NodeJS

node.jsresthttpsopenshift

提问by ssb

I am trying to write a NodeJS app which will talk to the OpenShift REST API using the request method in the https package. Here is the code:

我正在尝试编写一个 NodeJS 应用程序,它将使用 https 包中的请求方法与 OpenShift REST API 通信。这是代码:

var https = require('https');

var options = {
  host: 'openshift.redhat.com',
  port: 443,
  path: '/broker/rest/api',
  method: 'GET'
};

var req = https.request(options, function(res) {
  console.log(res.statusCode);
  res.on('data', function(d) {
    process.stdout.write(d);
  });
});
req.end();

req.on('error', function(e) {
  console.error(e);
});

But this is giving me an error (status code 500 is returned). When I did the same thing using curl on the command line,

但这给了我一个错误(返回状态代码 500)。当我在命令行上使用 curl 做同样的事情时,

curl -k -X GET https://openshift.redhat.com/broker/rest/api

I am getting the correct response from the server.

我从服务器得到正确的响应。

Is there anything wrong in the code?

代码有什么问题吗?

采纳答案by MiniGod

Comparing what headers curl and node sent, i found that adding:

比较 curl 和 node 发送的标头,我发现添加:

headers: {
    accept: '*/*'
}

to optionsfixed it.

options固定它。



To see which headers curl sends, you can use the -vargument.
curl -vIX GET https://openshift.redhat.com/broker/rest/api

要查看 curl 发送的标头,您可以使用该-v参数。
curl -vIX GET https://openshift.redhat.com/broker/rest/api

In node, just console.log(req._headers)after req.end().

在节点中,就console.log(req._headers)req.end().



Quick tip: You can use https.get(), instead of https.request(). It will set method to GET, and calls req.end()for you.

快速提示:您可以使用https.get(), 而不是https.request()。它将方法设置为GET,并呼叫req.end()您。