简体   繁体   English

节点 js 错误:不支持协议“https:”。 预期“http:”

[英]Node js Error: Protocol "https:" not supported. Expected "http:"

I am using IBM Bluemix to make a web service for a school project.我正在使用 IBM Bluemix 为学校项目制作 Web 服务。

My project needs to request a JSON from an API, so I can use the data it provides.我的项目需要从 API 请求 JSON,所以我可以使用它提供的数据。 I use the http get method for a data set, and I am not sure if it is working properly.我对数据集使用http get方法,我不确定它是否正常工作。

When I run my code, I get the message:当我运行我的代码时,我收到以下消息:

Error: Protocol "https:" not supported.错误:不支持协议“https:”。 Expected "http:"预期“http:”

What is causing it and how can I solve it?是什么原因造成的,我该如何解决?

Here is my .js file:这是我的.js文件:

// Hello.
//
// This is JSHint, a tool that helps to detect errors and potential
// problems in your JavaScript code.
//
// To start, simply enter some JavaScript anywhere on this page. Your
// report will appear on the right side.
//
// Additionally, you can toggle specific options in the Configure
// menu.

function main() {
  return 'Hello, World!';
}

main();/*eslint-env node*/

//------------------------------------------------------------------------------
// node.js starter application for Bluemix
//------------------------------------------------------------------------------

// HTTP request - duas alternativas
var http = require('http');
var request = require('request');

// cfenv provides access to your Cloud Foundry environment
// for more info, see: https://www.npmjs.com/package/cfenv
var cfenv = require('cfenv');

//chama o express, que abre o servidor
var express = require('express');

// create a new express server 
var app = express();

// serve the files out of ./public as our main files
app.use(express.static(__dirname + '/public'));

// get the app environment from Cloud Foundry
var appEnv = cfenv.getAppEnv();

// start server on the specified port and binding host
app.listen(appEnv.port, '0.0.0.0', function() {
    // print a message when the server starts listening
    console.log("server starting on " + appEnv.url);
});


app.get('/home1', function (req,res) {
    http.get('http://developers.agenciaideias.com.br/cotacoes/json', function (res2) {
        var body = '';
        res2.on('data', function (chunk) {
            body += chunk;
        });
        res2.on('end', function () {
            var json = JSON.parse(body);
            var CotacaoDolar = json["dolar"]["cotacao"];
            var VariacaoDolar = json["dolar"]["variacao"];
            var CotacaoEuro = json["euro"]["cotacao"];
            var VariacaoEuro = json["euro"]["variacao"];
            var Atualizacao = json["atualizacao"];

            obj=req.query; 

            DolarUsuario=obj['dolar'];
            RealUsuario=Number(obj['dolar'])*CotacaoDolar;

            EuroUsuario=obj['euro'];
            RealUsuario2=Number(obj['euro'])*CotacaoEuro;

            Oi=1*VariacaoDolar;
            Oi2=1*VariacaoEuro;

            if (VariacaoDolar<0) {
            recomend= "Recomenda-se, portanto, comprar dólares.";
            }

            else if (VariacaoDolar=0){
                recomend="";
            }

            else {
                recomend="Recomenda-se, portanto, vender dólares.";
                  }

            if (VariacaoEuro<0) {
            recomend2= "Recomenda-se, portanto, comprar euros.";
            }

            else if (VariacaoEuro=0){
                recomend2="";
            }
            else {
                recomend2="Recomenda-se,portanto, vender euros.";
                  }   

            res.render('cotacao_response.jade', {
                         'CotacaoDolar':CotacaoDolar,
                        'VariacaoDolar':VariacaoDolar,
                        'Atualizacao':Atualizacao,
                        'RealUsuario':RealUsuario,
                        'DolarUsuario':DolarUsuario,
                        'CotacaoEuro':CotacaoEuro,
                        'VariacaoEuro':VariacaoEuro,
                        'RealUsuario2':RealUsuario2,
                        'recomend':recomend,
                        'recomend2':recomend2,
                        'Oi':Oi,
                        'Oi2':Oi2
            });

        app.get('/home2', function (req,res) {
    http.get('https://www.quandl.com/api/v3/datasets/BCB/432.json?api_key=d1HxqKq2esLRKDmZSHR2', function (res3) {
        var body = '';
        res3.on('data', function (chunk) {
            body += chunk;
        });
        res3.on('end', function () {
            var x=json.dataset.data[0][1];
      console.log("My JSON is "+x); });

    });
    });
        });
    });
});

Here is a print of the error screen I get:这是我得到的错误屏幕的打印: 在此处输入图像描述

When you want to request an https resource, you need to use https.get , not http.get .当你想请求一个 https 资源时,你需要使用https.get ,而不是http.get

https://nodejs.org/api/https.html https://nodejs.org/api/https.html

作为向从 Google 寻求解决方案的任何人的附带说明...确保您没有使用带有https请求的http.Agent ,否则您将收到此错误。

The reason for this error is that you are trying to call a HTTPS URI from a HTTP client.此错误的原因是您尝试从 HTTP 客户端调用 HTTPS URI。 The ideal solution would have been for a generic module to figure out the URI protocol and take the decision to use HTTPS or HTTP internally.理想的解决方案是让一个通用模块找出 URI 协议并在内部决定使用 HTTPS 或 HTTP。

The way I overcame this problem is by using the switching logic on my own.我克服这个问题的方法是自己使用切换逻辑。 Below is some code which did the switching for me.下面是一些为我进行切换的代码。

    var http = require('http');
    var https = require('https');
    // Setting http to be the default client to retrieve the URI.
    var url = new URL("https://www.google.com")
    var client = http; /* default  client */
    // You can use url.protocol as well 
    /*if (url.toString().indexOf("https") === 0){
                client = https;
    }*/
    /* Enhancement : using the  URL.protocol  parameter
     * the  URL  object ,  provides a  parameter url.protocol that gives you 
     * the protocol  value  ( determined  by the  protocol ID  before 
     * the ":" in the  url. 
     * This makes it easier to  determine the protocol, and to  support other  
     * protocols like ftp ,  file  etc) 
     */
   client = (url.protocol == "https:") ? https : client; 
    // Now the client is loaded with the correct Client to retrieve the URI.
    var req = client.get(url, function(res){
        // Do what you wanted to do with the response 'res'.
        console.log(res);
    });

Not sure why, but the issue for me happened after updating node to version 17, i was previously using version 12.不知道为什么,但我的问题是在将节点更新到版本 17 后发生的,我之前使用的是版本 12。

In my setup, i have node-fetch using HttpsProxyAgent as an agent in the options object.在我的设置中,我使用HttpsProxyAgent作为选项对象中的代理来获取节点

options['agent'] = new HttpsProxyAgent(`http://${process.env.AWS_HTTP_PROXY}`)
response = await fetch(url, options)

Switching back to node 12 fixed the problem:切换回节点 12 解决了问题:

nvm use 12.18.3

I got this error while deploying the code.部署代码时出现此错误。

INFO    error=> TypeError [ERR_INVALID_PROTOCOL]: Protocol "https:" not supported. Expected "http:"
at new NodeError (node:internal/errors:372:5)

To fix this issue, I have updated the "https-proxy-agent" package version to "^5.0.0"为了解决这个问题,我已将“https-proxy-agent”包版本更新为“^5.0.0”

Now the error was gone and it's working for me.现在错误消失了,它对我有用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Nodejs 错误:不支持协议“http:”。 预期“https:” - Nodejs Error: Protocol “http:” not supported. Expected “https:” Azure SpeechSynthesizer 错误 HTTP:不支持。 预期的 HTTPS:NPM `microsoft-cognitiveservices-speech-sdk` - Azure SpeechSynthesizer Error HTTP: not supported. Expected HTTPS: NPM `microsoft-cognitiveservices-speech-sdk` '不支持 ES 模块的 require()。 ' Node.js、快递、swagger-jsdoc 出错 - 'require() of ES modules is not supported. ' error with Node.js, express, swagger-jsdoc AngularJS错误:仅支持协议方案的跨源请求:http,数据,chrome扩展,https - AngularJS Error: Cross origin requests are only supported for protocol schemes: http, data, chrome-extension, https DiscordAPIError:无效的表单正文 embed.image.url:不支持方案“[对象响应]”。 方案必须是 ('http', 'https') 之一 - DiscordAPIError: Invalid Form Body embed.image.url: Scheme “[object response]” is not supported. Scheme must be one of ('http', 'https') × 错误:Alchemy URL 协议必须是 http、https、ws 或 wss 之一。 收到:未定义的 React.js - × Error: Alchemy URL protocol must be one of http, https, ws, or wss. Recieved: undefined React.js 协议HTTP和https不匹配 - Mismatch protocol http and https js脚本的http和https错误 - Error with http and https for js scripts 如何在节点js中将http重定向到https - How to redirect http to https in node js CORS 错误:“请求仅支持协议方案:http…”等 - CORS Error: “requests are only supported for protocol schemes: http…” etc
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM