Vue 2 devServer 代理不适用于 websocket

Vue 2 devServer proxying does not work for websocket

我在 python 运行 中有一个简单的网络服务器,例如 127.0.0.1:8080。 我可以提供 http 请求和网络套接字。 这是服务器路由的示例。

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

我的应用程序的前端部分在 Vue 2 JS 中。 我为代理开发服务器设置了 vue.config.js 文件。

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
    }
  }
}

当我发出http请求时,例如

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

一切正常,但如果我想设置 websocket 连接

soc = new WebSocket('/ws'); 

我收到错误

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

对于 websockets,我的设置不起作用。

连接已建立,如果提供完整地址,一切正常。

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

我已经阅读了很多文章,但没有成功解决我的问题 - 我该如何为 Vue JS 开发服务器代理 websocket 连接。

您应该将 WebSocket 实例化为 ws = new WebSocket('ws://' + window.location.host + '/ws');