【发布时间】:2022-01-22 01:27:28
【问题描述】:
我正在关注套接字 io 文档 虽然仍然出现错误
polling-xhr.js:157 GET http://localhost:3000/socket.io/?EIO=4&transport=polling&t=NtNlWd6 404(未找到)
虽然我被卡住了,但我的事情很简单
下面是我的代码
server.js
const express = require('express'); //Line 1
const app = express(); //Line 2
const port = process.env.PORT || 5000; //Line 3
const http = require('http').Server(app);
const io = require('socket.io')(http);
//Whenever someone connects this gets executed
io.on('connection', function(socket) {
console.log('A user connected');
//Whenever someone disconnects this piece of code executed
socket.on('disconnect', function () {
console.log('A user disconnected');
});
});
// This displays message that the server is running and listening to specified port
app.listen(port, () => console.log(`Listening on port ${port}`)); //Line 6
// create a GET route
app.get('/express_backend', (req, res) => { //Line 9
console.log("printing from the server f3f134g")
res.send({ express: "YOUR EXPRESS BACKEND IS CONNECTED TO REACT" }); //Line 10
}); //Line 11
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta
name="viewport"
content="width=device-width, initial-scale=1"
/>
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Web site created using create-react-app"
/>
<link
rel="apple-touch-icon"
href="%PUBLIC_URL%/logo192.png"
/>
</head>
<body>
<script src="https://cdn.socket.io/4.4.0/socket.io.min.js" integrity="sha384-1fOn6VtTq3PWwfsOrk45LnYcGosJwzMHv+Xh/Jx5303FVOXzEnw0EpLv30mtjmlj" crossorigin="anonymous"></script>
<script>
var socket = io();
</script>
<div id="root"></div>
</body>
</html>
请同时注意
```<script src="/socket.io/socket.io.js"></script>```
和
<script src="https://cdn.socket.io/4.4.0/socket.io.min.js" integrity="sha384-1fOn6VtTq3PWwfsOrk45LnYcGosJwzMHv+Xh/Jx5303FVOXzEnw0EpLv30mtjmlj" crossorigin="anonymous"></script>
报错
【问题讨论】:
-
你的 PORT 环境变量是否设置为 3000?
-
不确定,是吗? , 常量端口 = process.env.PORT || 5000;在我的 server.js 代码中
-
这可能是问题所在。您看到的错误表明它尝试连接到端口 3000,但在您的服务器代码中它将使用端口 5000除非 PORT 环境变量设置为不同的值。
-
好的,那么解决方案是什么?如果我更改 const port = process.env.PORT || 则设置它3000 //更改为 3000 我得到一个不同的问题:代理错误:无法将请求 /socket.io/socket.io.js 从 localhost:3000 代理到 localhost:5000。请参阅nodejs.org/api/errors.html#errors_common_system_errors 了解更多信息(ECONNREFUSED)。
-
你可能有 React WDS 使用端口 3000,那么你的服务器不应该使用相同的端口。您可以将此行添加到您的 React 应用程序的 package.json:
"proxy": "http://localhost:<port-that-your-server-uses>",例如"proxy": "http://localhost:5000"