如何解决尝试代理 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 举报,一经查实,本站将立刻删除。