Nodejs错误:协议"http:"不受支持的.预计“https:“

Nodejs Error: Protocol "http:" not supported. Expected "https:"

本文关键字:quot 预计 https 支持 http 错误 协议 Nodejs      更新时间:2023-09-26

我正在使用请求模块的node.js和时间的时间我得到未捕获的错误(仅在生产,也许在node.js更新后)

节点版本:0.12.4,请求版本:2.55.0

1000-2000个请求可以成功执行,但是我得到这样的错误:

Error: Protocol "http:" not supported. Expected "https:".
    at new ClientRequest (_http_client.js:75:11)
    at Object.exports.request (http.js:49:10)
    at Request.start (/path/node_modules/request/request.js:963:30)
    at Request.end (/path/node_modules/request/request.js:1531:10)
    at end (/path/node_modules/request/request.js:734:14)
    at Immediate._onImmediate (/path/node_modules/request/request.js:748:7)
    at processImmediate [as _immediateCallback] (timers.js:358:17)"

我该如何修复它?它为什么会出现?谢谢)

这是由于使用SSL运行应用程序但通过普通HTTP调用它造成的。您需要进行检查,以确定客户端是使用HTTP还是HTTPS,然后修改代码以适应。

应该这样做:

var express = require('express')
    , http = require('http')
    , https = require('https')
    , app = express();
http.createServer(app);
https.createServer({ ... }, app);

然后当你处理你的请求时,做一些像

app.get('/your-route', function(req, res) {
    if (req.secure) {
        var req = https.get(url, function(res) { ... });
    } else {
        var req = http.get(url, function(res) { ... });
    }
});

req.secure标识连接是否安全。注意我们是如何根据连接类型使用httpshttp的。

仅供参考,我得到了一个类似的错误

TypeError [ERR_INVALID_PROTOCOL]: Protocol "http:" not supported. Expected "https:"
    at new ClientRequest (_http_client.js:120:11)
    at request (http.js:42:10)
    at ..../node_modules/node-fetch/lib/index.js:1432:15
    at new Promise (<anonymous>)
    at fetch (..../node_modules/node-fetch/lib/index.js:1401:9)
    at ClientRequest.<anonymous> (..../node_modules/node-fetch/lib/index.js:1532:15)
    at ClientRequest.emit (events.js:198:13)
    at HTTPParser.parserOnIncomingClient [as onIncoming] (_http_client.js:565:21)
    at HTTPParser.parserOnHeadersComplete (_http_common.js:111:17)
    at TLSSocket.socketOnData (_http_client.js:451:20)
    at TLSSocket.emit (events.js:198:13)
    at addChunk (_stream_readable.js:288:12)
    at readableAddChunk (_stream_readable.js:269:11)
    at TLSSocket.Readable.push (_stream_readable.js:224:10)
    at TLSWrap.onStreamRead (internal/stream_base_commons.js:94:17)

,这是由于获取指令

中的url中出现了愚蠢的拼写错误。
        fetch(`https://xxx@yyy.com`, {
            method: 'post',
            body: JSON.stringify(eventLogEntry),
            headers: { 'Content-Type': 'application/json' },
            agent: agent
        })

当我将url固定为xxx.yyy.com时,我的问题就解决了