Home > Back-end >  Vue 2 devServer proxying does not work for websocket
Vue 2 devServer proxying does not work for websocket

Time:11-07

I have simple web server in python running for example on 127.0.0.1:8080. I can serve http-requests and web sockets. This is example of server routes.

...
web.route('*', '/ws', ws_handler),
web.route('*', '/api/some_url', http_handler)
...

And I have frontend part of my application in Vue 2 JS. I set up vue.config.js file for proxying dev server.

const host = "127.0.0.1"
const port = 8080

devServer: {
  proxy: {
    "/api": {
      target:`http://${host}:${port}/`,
      secure:false
    },
    "/ws": {
      target:`ws://${host}:${port}/`,
      ws:true,
      secure:false,
      changeOrigin:true
    }
  }
}

When I make http requests, for example

let res = await axios.get('/api/some_url');

everything works fine, but if I want to set up websocket connection

soc = new WebSocket('/ws'); 

I got error

Failed to construct 'WebSocket': The URL '/ws' is invalid.

For websockets my settings does not work.

Connection sets up and everything works fine if full address is provided.

soc = new WebSocket('ws://127.0.0.1:8080/ws');

I have read many articles and had no success for resolve my issue - how can I do proxying websocket connection for Vue JS dev server.

CodePudding user response:

You should instantiate your WebSocket as ws = new WebSocket('ws://' window.location.host '/ws');

  • Related