如何在 vue-cli 应用程序中正确设置 devServer 以进行 WebSocket 代理

问题描述 投票:0回答:2

我有一个 Node.JS 服务器在 http://localhost:8080 运行,有 2 条路由:

  • "/"
    :服务/public/index.html.
  • "/rest"
    :返回
    { ok: true }

此服务器还在同一端口上运行 Websocket 连接。在 index.html 中,我使用 const socket = new WebSocket("ws://" + window.location.host)

 连接到服务器。

当我运行此服务器并访问

http://localhost:8080 时,以下内容有效:

    提供索引:是✅
  • 返回 JSON:是 ✅
  • WebSocket 消息传递:是 ✅

此外,我还在开发模式下在

http://localhost:8079 运行 vue-cli 应用程序,并使用以下 vue.config.js 配置:

... devServer: { port: 8079, "/": { target: "http://localhost:8080/", ws: true }, }
当我运行此应用程序并访问 

http://localhost:8079 时,会发生以下情况:

    索引已提供:是✅,这意味着代理正在为该路由工作。
  • 返回 JSON:是 ✅,这意味着代理正在为该路由工作。
  • WebSockets 消息传递:否 ❌,我收到错误
  • “与 'ws://localhost:8079/' 的 WebSocket 连接失败:连接建立时出错:net::ERR_CONNECTION_REFUSED”

我做错了什么?我该如何解决它?

如您所见,我已经包含了

ws: true

,它也用于代理 WebSocket 连接。

node.js websocket connection http-proxy
2个回答
4
投票
我在 vue.config.js 中有以下内容:

devServer: { proxy: { '^/': { target: 'http://localhost:8089', ws: true, changeOrigin: true } } }
Websocket 后端运行在端口 8089 上。
所有 ws 流量都代理到后端。


0
投票
提示:

要从浏览器获取协议/主机名/端口,请使用 webSocketURL: 'auto://0.0.0.0:0/ws'。

https://webpack.js.org/configuration/dev-server/#devserverserver

© www.soinside.com 2019 - 2024. All rights reserved.