Node.js错误:不支持协议“http:”。预期为“https:”。

7

我正在使用 node.js 的 request 模块,但不时地(仅在生产环境中,可能是在 node.js 更新后)会遇到未捕获的错误。

Node 版本:0.12.4,request 版本: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)"

我该如何修复它?为什么会出现这个问题?谢谢 :)

你是否正在使用socks5-https-client与Request?https://github.com/mattcg/socks5-https-client/issues/6 - chedabob
2个回答

8
这是由于使用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


3

顺便说一下,我遇到了类似的错误

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
        })

当我修复了到xxx.yyy.com的网址时,我的问题消失了。


如果没有你的答案,我打赌我会花上几天时间来解决这个问题。 - Sergey Pleshakov

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接