Proxy websockets connection within webpack-dev-server

前提是你 提交于 2020-12-02 04:46:15

问题


Is it possible to proxy websocket connections within the webpack dev server? I know how to proxy regular HTTP requests to another backend but it's not working for websockets, presumably because the target in the proxy configuration starts with http://...


回答1:


Version 1.15.0 of the webpack-dev-server supports proxying websocket connections. Add the following to your configuration:

devServer: {
  proxy: {
    '/api': {
       target: 'ws://[address]:[port]',
       ws: true
    },
  },
}



回答2:


Webpack dev server does not support proxying ws connections yet.

Until then, you can implement proxying manually, by adding additional http-proxy to webpack server:

  • Add new dependency to package.json:

    "http-proxy": "^1.11.2"
    
  • Proxy websocket connections manually by listening to upgrade events

    // existing webpack-dev-server setup
    // ...
    var server = new WebpackDevServer(...);
    
    proxy = require('http-proxy').createProxyServer();
    server.listeningApp.on('upgrade', function(req, socket) {
      if (req.url.match('/socket_url_to_match')) {
        console.log('proxying ws', req.url);
        proxy.ws(req, socket, {'target': 'ws://localhost:4000/'});
      }
    });
    //start listening
    server.listen(...)   
    

NOTE (after using this for some time)

There is an issue with proxying websockets as socket.io is used by WebpackDevServer to notify browser of code changes. socket.io may conflict with proxying websockets; in my case, connections were being dropped before handshake was returned from my server unless it responded very quickly.

At that point, I just ditched WebpackDevServer and used custom implementation based on react-hot-boilerplate




回答3:


@Mr. Spice's answer is correct. But it can be further simplified, check http-proxy-middleware, it can be set as following, i.e. just add ws: true and keep other settings as usual.

// proxy middleware options
var options = {
        target: 'http://www.example.org', // target host
        changeOrigin: true,               // needed for virtual hosted sites
        ws: true,                         // proxy websockets
        ...


来源:https://stackoverflow.com/questions/31654239/proxy-websockets-connection-within-webpack-dev-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!