尝试代理 websocket 并且在 setupProxy 中未建立连接

问题描述

我有我的 React 应用程序,它是由 setupProxy.js 设置的,它应该代理我的 ws 后端。但不知何故,连接没有建立,但是 http 和 https 请求工作得很好。附上代码示例:
setupProxy.js

const { createProxyMiddleware } = require('http-proxy-middleware')

module.exports = (app) => {
    app.use(
        '/sockets',createProxyMiddleware({
            target: 'ws://localhost:8080',pathRewrite: (path) => path.replace('/sockets',''),secure: false,changeOrigin: true
        })
    );

    app.use(
        '/hello',createProxyMiddleware({
            target: 'http://localhost:8080/hello',pathRewrite: (path) => path.replace('/hello',changeOrigin: true
        })
    )
}

App.tsx

import React from 'react';

const App: React.FC = () => {

  React.useEffect(() => {
    new WebSocket(`ws://${window.location.host}/sockets`);
    fetch('/hello').then(value => value.json()).then(res => console.log('response: ',res))
  },[])

  return (
    <div>
      Hello World
    </div>
  )
}

export default App;

后端/index.js

const express = require('express');
const app = express();
const http = require('http');
const server = http.createServer(app);
const { Server } = require("socket.io");
const io = new Server(server);

app.get('/hello',(req,res) => res.send({hello: 'hello'}))

io.on('connection',(socket) => {
    console.log('a user connected');
    socket.disconnect();
});

server.listen(8080,() => {
    console.log('listening on *:8080');
});

提前谢谢?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)