node.js TypeError [ERR_INVALID_PROTOCOL]: Protocol "http:" not supported. Expected "https:

Viewed 4110

Given below Node.js code i was try to use https as the project required but getting error

TypeError [ERR_INVALID_PROTOCOL]: Protocol "http:" not supported. Expected "https:"

const express = require("express");
var https = require("https");


const app = express();


app.get("/", function(req, res) {

    const url = "http://api.openweathermap.org/data/2.5/weather?q=Gwalior&appid=4b01458a2b74d57ff37f136f382ac4d5&units=metric";

    https.get(url, function(response) {
        console.log(response.statusCode)
    });
    res.send("Server is Up and Running");
})



app.listen(3000, function() {
    console.log("Server is running on port 3000.");
})

Complete Error stack trace:

TypeError [ERR_INVALID_PROTOCOL]: Protocol "http:" not supported. Expected "https:"
    at new ClientRequest (_http_client.js:151:11)
    at request (https.js:316:10)
    at Object.get (https.js:320:15)
    at C:\Users\Public\Documents\WeatherProject\app.js:12:10
    at Layer.handle [as handle_request] (C:\Users\Public\Documents\WeatherProject\node_modules\express\lib\router\layer.js:95:5)
    at next (C:\Users\Public\Documents\WeatherProject\node_modules\express\lib\router\route.js:137:13)
    at Route.dispatch (C:\Users\Public\Documents\WeatherProject\node_modules\express\lib\router\route.js:112:3)
    at Layer.handle [as handle_request] (C:\Users\Public\Documents\WeatherProject\node_modules\express\lib\router\layer.js:95:5)
    at C:\Users\Public\Documents\WeatherProject\node_modules\express\lib\router\index.js:281:22
    at Function.process_params (C:\Users\Public\Documents\WeatherProject\node_modules\express\lib\router\index.js:335:12)

But if i am using http its working fine even i have tried with node install https (still not work)

2 Answers

The problem with the code is that you are making https request and in your url you are using "http" instead of "https". So if you change your url to "https" it should work.

https://api.openweathermap.org/data/2.5/weather?q=Gwalior&appid=4b01458a2b74d57ff37f136f382ac4d5&units=metric

I know you have figured this out but for the purpose of those that might run into this in the future - So the code should be:

const express = require("express");
var https = require("https");


const app = express();


app.get("/", function(req, res) {

    const url = "https://api.openweathermap.org/data/2.5/weather?q=Gwalior&appid=4b01458a2b74d57ff37f136f382ac4d5&units=metric";

    https.get(url, function(response) {
        console.log(response.statusCode)
    });
    res.send("Server is Up and Running");
})



app.listen(3000, function() {
    console.log("Server is running on port 3000.");
})

Your doing https request and your url starts with http:// when it should be https://.

Related