簡體   English   中英

node.js TypeError [ERR_INVALID_PROTOCOL]:不支持協議“http:”。 預計“https:

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

下面給出 Node.js 代碼,我嘗試使用 https 作為項目所需,但出現錯誤

TypeError [ERR_INVALID_PROTOCOL]:不支持協議“http:”。 預期“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.");
})

完整的錯誤堆棧跟蹤:

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)

但是,如果我使用 http 它工作正常,即使我已經嘗試使用節點安裝 https (仍然無法正常工作)

你做的 https 請求和你的 url 以http://開頭,而它應該是https://

代碼的問題是您正在發出 https 請求,並且在您的 url 中您使用的是"http"而不是"https" 因此,如果您將 url 更改為"https" ,它應該可以工作。

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

我知道您已經解決了這個問題,但是出於將來可能會遇到此問題的目的-因此代碼應該是:

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.");
})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM