nathantsoi / vue-native-websocket

native websocket with vuex integration
944 stars 163 forks source link

How to proxy with webpack dev server? #44

Open apo1967 opened 6 years ago

apo1967 commented 6 years ago

The WebSocket that is created in the Observer tests the connection url and must contain both schema and authority, I can not pass a relative path like "/ws-endpoint". Therefore I can not use the webpack dev server to proxy the call although it is able to deal with the ws protocol, see https://github.com/chimurai/http-proxy-middleware#options. Is there any way to deal with this?

g3rd commented 6 years ago

I've borrow this from django-channels to add relative support:

  (url) => {
      let _url;
      // Use wss:// if running on https://
      const scheme = window.location.protocol === 'https:' ? 'wss' : 'ws';
      const base_url = `${scheme}://${window.location.host}`;
      if (url === undefined) {
        _url = base_url;
      } else {
        // Support relative URLs
        if (url[0] == '/') {
          _url = `${base_url}${url}`;
        } else {
          _url = url;
        }
      }
      return _url;
    }

Then in webpack conf:

devServer: {
  ...
  proxy: {
      '/ws/': {
        target: 'ws://localhost:8000',
        secure: false,
        ws: true,
      }
}
atyshka commented 4 years ago

@g3rd Where did you add the first code snippet?