gpt4 book ai didi

node.js - 带有 React 和 Express 的套接字 IO。 ReactJS 错误 : Could not proxy request/socket. io/?EIO=4..... 来自本地主机 :3000 to http://127. 0.0.1:4000

转载 作者:行者123 更新时间:2023-12-04 03:43:06 33 4
gpt4 key购买 nike

我正在尝试在我的 creat-react-app 前端与我的 express 后端之间建立连接。我将代理设置为我的后端服务的端口 (4000)。当我运行该应用程序时,前端出现代理错误:

Proxy error: Could not proxy request /socket.io/?EIO=4&transport=polling&t=NRRFdVj&sid=CJzhACsXDlXmP4aRAAAQ from localhost:3000 to http://127.0.0.1:4000.
See https://nodejs.org/api/errors.html#errors_common_system_errors for more information (ECONNRESET).

这是我的代码:

后端/index.js

const app = require('express')();
const http = require('http');
const server = http.createServer(app);

const io = require('socket.io')(server);

io.on('connection', (socket) => {
console.log('New WS connection....');
});

server.listen(4000, () => console.log('Server running on port 4000'));

前端/App.js

import React from 'react';
import socketClient from 'socket.io-client';

const App = () => {
const socket = socketClient();
return <div>hello</div>;
};

export default App;

前端/package.json

{
"name": "frontend",
"proxy": "http://127.0.0.1:4000/",
"version": "0.1.0",
"private": true,
"dependencies": {
"@testing-library/jest-dom": "^5.11.8",
"@testing-library/react": "^11.2.2",
"@testing-library/user-event": "^12.6.0",
"react": "^17.0.1",
"react-dom": "^17.0.1",
"react-scripts": "4.0.1",
"socket.io-client": "^3.0.5",
"web-vitals": "^0.2.4"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}

当我从后端获取数据时代理工作正常,但在这种情况下使用它时会发生代理错误...

最佳答案

试试下面的代码。您没有在 socketClient([URL][,options]); 上添加 URL 参数;

import React from 'react';
import socketClient from 'socket.io-client';

const App = () => {
const socket = socketClient("http://localhost:4000");
return <div>hello</div>;
};

export default App;

关于node.js - 带有 React 和 Express 的套接字 IO。 ReactJS 错误 : Could not proxy request/socket. io/?EIO=4..... 来自本地主机 :3000 to http://127. 0.0.1:4000,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65606993/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com