vue.js - 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 连接。
解决方案
您应该将您的 WebSocket 实例化为ws = new WebSocket('ws://' + window.location.host + '/ws');
推荐阅读
- angular - 对角度无线电变化的记录进行排序
- java - 将当前视图保存为位图
- r - 将调查列表对象转换为数据框并将字符串列拆分为多列
- python - 将 pandas 数据框列从 int 更改为 string 并保存为字符串 csv
- python - ModuleNotFoundError,但它在 anaconda (jupyter) 中运行
- excel - MS Graph API 使用范围保护 Excel 工作表函数
- python - 是否可以使用 BeautifulSoup 遍历 python 列表?
- c# - 如何删除列表内字符串中的所有字符串实例?
- sas - SAS 中所选日期范围的数据缺失
- javascript - 当文本有限时,jQuery隐藏显示更多按钮