首页 > 解决方案 > Vue 2 devServer 代理不适用于 websocket

问题描述

我在 python 中运行了简单的 Web 服务器,例如在 127.0.0.1:8080 上运行。我可以提供 http-requests 和 web sockets。这是服务器路由的示例。

...
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 连接。

标签: vue.jsvuejs2

解决方案


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


推荐阅读