http-party / node-http-proxy

A full-featured http proxy for node.js
https://github.com/http-party/node-http-proxy
Other
13.88k stars 1.97k forks source link

node-http-proxy does not support websockets? #1200

Open kamilml opened 7 years ago

kamilml commented 7 years ago

I got this error: WebSocket connection to 'ws://mydomain.com/socket.io/?EIO=3&transport=websocket&sid=EhP73S4_-XoHOIisAAAa' failed: Error during WebSocket handshake: Unexpected response code: 520

I am actually using Next.js with an express.js server. And use http-proxy to proxy a conection to my socket.io server.

http conection works but the upgrade don't

this is my server configuration:

'use strict'
const express = require('express')
const next = require('next')
const cookieParser = require('cookie-parser')
const httpProxy = require('http-proxy')
const apiProxy = httpProxy.createProxy({
  changeOrigin: true,
  ws: true
})
const proxySocket = new httpProxy.createProxyServer({
  target: 'ws://localhost:8880'
})

const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()

const PORT = require('./next.config').PORT
const BASE_URL = require('./next.config').BASE_URL

app.prepare()
.then(() => {
  const server = express()
  server.use(cookieParser())

  // api server
  server.use('/api/*', (req, res) => {
    apiProxy.web(req, res, { target: 'http://localhost:4000/'+req.params[0] })
  })

  // websockets
  server.use('/socket.io/*', (req, res) => {
    apiProxy.web(req, res, { target: 'http://localhost:8880/socket.io/'+req.params[0] })
  })
  server.on('upgrade', function (req, socket, head) {
    console.log('upgradeando', socket)
    proxySocket.ws(req, socket, head)
  })

  server.get('*', (req, res) => handle(req, res))
  server.listen(PORT, (err) => {
    if (err) throw err
    console.log('> Ready on http://localhost:'+PORT)
  })
})
.catch((ex) => {
  console.error(ex.stack)
  process.exit(1)
})
kamilml commented 7 years ago

you can see here my socket work in http protocol but when this try to upgrade to ws protocol, this fail error

vogrelord commented 6 years ago

Well, you are trying to attach event to express app, not server. You can use https://github.com/chimurai/http-proxy-middleware, or find the approach there