如何处理节点的http-proxy中的connect方法以允许通过代理进行Websocket连接?

时间:2019-03-22 09:48:06

标签: node.js websocket node-http-proxy

我正在尝试使用node-http-proxy模块制作一个HTTP代理服务器,但我也想在我的代理服务器中支持WebSocket。为此,我在upgrade方法上注册了一个事件侦听器,例如以下代码,如果我将本地代理服务器的URL传递给WebSocket的代理密钥,则该监听器可以正常工作

httpServer.on("upgrade", function(req, sock, head) {
    console.log("upgrade called")

    let reqUrl = req.url
    let hostPath = reqUrl.split("//")[1]
    let wsUrl = `ws://${hostPath}`

    proxy.ws(req,sock,head, {
            target: wsUrl,
            ws: true,
            autoRewrite: true,
            changeOrigin: true
    })
})

但是,当我在google-chrome中将本地proxyServer的URL用作HTTP代理URL,然后尝试使用任何WebSocket代码时,它不会调用代理的升级方法,而是chrome调用connect方法。因此,我还侦听了HTTP服务器的connect方法,并在connect方法的回调中做了很少的修改就编写了相同的代码。您可以在下面看到我的代码

httpServer.on("connect", (req, clientSocket, head) => {
    console.log("connect called")

    let reqUrl = req.url
    let wsUrl = `ws://${reqUrl}`

    proxy.ws(req,clientSocket,head,
        {
            target: wsUrl,
            ws: true,
            autoRewrite: true,
            changeOrigin: true
        })
})

但仍然,我的代理不适用于WebSockets。如果我尝试在浏览器控制台中运行var ws=new WebSocket('ws://echo.websocket.org/');,则会收到以下错误WebSocket connection to 'ws://echo.websocket.org/' failed: Error in connection establishment: net::ERR_EMPTY_RESPONSE:这次调用了connect方法,服务器端没有错误,但是客户端的WebSocket没有连接

所以我想知道,我该如何处理connect方法以允许通过我的代理进行WebSocket连接

0 个答案:

没有答案