我正在尝试编写一个 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);
});
但这给了我一个错误(返回状态码 500)。当我在命令行上使用 curl 做同样的事情时,
curl -k -X GET https://openshift.redhat.com/broker/rest/api
我从服务器得到正确的响应。
代码有问题吗?
最佳答案
比较什么 headers curl 和 node 发送,我发现添加:
headers: {
accept: '*/*'
}
到 options
修复它。
要查看 curl 发送哪些 header ,您可以使用 -v
参数。
curl -vIX GET https://openshift.redhat.com/broker/rest/api
在 Node 中,只是 console.log(req._headers)
在 req.end()
之后。
快速提示:您可以使用 https.get()
,而不是 https.request()
。它将方法设置为GET
,并为你调用req.end()
。
关于node.js - NodeJS 中的 HTTPS 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12851858/