노드 js 오류: 프로토콜 "https:"가 지원되지 않습니다.예상 "http:"
저는 학교 프로젝트를 위한 웹 서비스를 만들기 위해 IBM 블루믹스를 사용하고 있습니다.
제 프로젝트는 API에 JSON을 요청해야 하기 때문에 제공되는 데이터를 사용할 수 있습니다.사용하다http get
올바르게 동작하고 있는지 어떤지는 잘 모르겠습니다.
코드를 실행하면 다음과 같은 메시지가 나타납니다.
오류: 프로토콜 "https:"은 지원되지 않습니다.예상 "http:"
원인은 무엇이며 어떻게 해결할 수 있습니까?
여기 제 것이 있습니다..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); });
});
});
});
});
});
표시되는 에러 화면의 인쇄를 다음에 나타냅니다.
https 리소스를 요청하려면https.get
,것은 아니다.http.get
.
https://nodejs.org/api/https.html
Google에서 솔루션을 찾고 있는 분들을 위한 참고 사항으로...http.Agent
와 함께https
요청하지 않으면 이 오류가 발생합니다.
이 에러의 원인은, HTTP 클라이언트에서 HTTPS URI 를 콜 하려고 하고 있기 때문입니다.이상적인 솔루션은 범용 모듈이 URI 프로토콜을 파악하여 내부적으로 HTTPS 또는 HTTP를 사용할지 결정하는 것입니다.
이 문제를 극복하는 방법은 스스로 스위칭 로직을 사용하는 것입니다.아래는 나를 위해 전환한 코드입니다.
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);
});
이유는 모르겠지만, 이전에 버전 12를 사용하고 있던 버전 17로 노드를 업데이트한 후 문제가 발생했습니다.
설정에서 옵션 개체의 에이전트로 HttpsProxyAgent를 사용하여 노드 가져오기를 수행했습니다.
options['agent'] = new HttpsProxyAgent(`http://${process.env.AWS_HTTP_PROXY}`)
response = await fetch(url, options)
노드 12로 돌아가면 문제가 해결되었습니다.
nvm use 12.18.3
코드를 전개중에 이 에러가 발생했습니다.
INFO error=> TypeError [ERR_INVALID_PROTOCOL]: Protocol "https:" not supported. Expected "http:"
at new NodeError (node:internal/errors:372:5)
이 문제를 해결하기 위해 "https-proxy-agent" 패키지 버전을 "^5.0.0"으로 업데이트했습니다.
이제 오류는 사라졌고 나에게도 효과가 있다.
언급URL : https://stackoverflow.com/questions/34147372/node-js-error-protocol-https-not-supported-expected-http
'programing' 카테고리의 다른 글
Bower - EPERM, 링크 해제 오류 (0) | 2023.03.08 |
---|---|
예약 가능 날짜별 woocommerce 예약 쿼리 (0) | 2023.03.08 |
React-Redux 복합(심층) 상태 객체 (0) | 2023.03.08 |
Python에서 JSON을 문자열로 변환 (0) | 2023.03.08 |
wp_list_filength()가 작동하지 않습니다. (0) | 2023.03.08 |