【问题标题】:How to correctly setup devServer for WebSocket proxying in a vue-cli app如何在 vue-cli 应用程序中为 WebSocket 代理正确设置 devServer
【发布时间】:2020-12-31 12:40:21
【问题描述】:

我有一个 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.config.js 以开发模式运行 vue-cli 应用程序 配置:

...
devServer: {
  port: 8079,
  "/": {
    target: "http://localhost:8080/",
    ws: true
  },
}

当我运行这个应用程序并访问 http://localhost:8079 时,会发生以下情况:

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

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

如您所见,我已经包含了 ws: true,它也用于代理 WebSocket 连接。

【问题讨论】:

    标签: node.js websocket connection http-proxy


    【解决方案1】:

    我在 vue.config.js 中有以下内容:

      devServer: {
        proxy: {
          '^/': {
            target: 'http://localhost:8089',
            ws: true,
            changeOrigin: true
          }
        }
      }
    

    websocket 后端在 8089 端口上运行。 所有 ws 流量都代理到后端。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-27
      • 2021-06-17
      • 2021-10-21
      • 1970-01-01
      • 2019-01-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多