ben*_*mer 11 node.js socket.io reactjs
我正在关注套接字 io 文档,但仍然收到错误
polling-xhr.js:157 GET http://localhost:3000/socket.io/?EIO=4&transport=polling&t=NtNlWd6 404(未找到)
虽然我被困住了,但我的事情很简单
下面是我的代码
服务器.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
Run Code Online (Sandbox Code Playgroud)
索引.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>
Run Code Online (Sandbox Code Playgroud)
请注意两者
```<script src="/socket.io/socket.io.js"></script>```
Run Code Online (Sandbox Code Playgroud)
和
<script src="https://cdn.socket.io/4.4.0/socket.io.min.js" integrity="sha384-1fOn6VtTq3PWwfsOrk45LnYcGosJwzMHv+Xh/Jx5303FVOXzEnw0EpLv30mtjmlj" crossorigin="anonymous"></script>
Run Code Online (Sandbox Code Playgroud)
给出一个错误
tro*_*mgy 36
问题出在您的服务器代码中。
您将 socket.io 绑定到http,但仅app侦听端口 (5000)。您需要监听http该端口。
更改这一行:
app.listen(port, () => console.log(`Listening on port ${port}`));
Run Code Online (Sandbox Code Playgroud)
到
http.listen(port, () => console.log(`Listening on port ${port}`));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
34615 次 |
| 最近记录: |