我正在建立一个论坛,两个连接后的用户可以发布状态,然后对他们进行评论。对于评论,我使用了socket.io。
在控制台中,我每隔几秒钟就会收到这个错误:
Failed to load resource: net::ERR_CONNECTION_REFUSED
GET http://localhost/socket.io/?EIO=4&transport=polling&t=O05nump net::ERR_CONNECTION_REFUSED
如何修复此错误?
我在套接字服务器上安装了express、nodemon和socket.io。
package.json
{
"name": "socket",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.17.3",
"nodemon": "^2.0.15",
"socket.io": "^4.4.1"
}
}
app.js
const io = require("socket.io")(4000, {
cors: {
origin: "http//localhost:3000",
},
});
io.on('connection', (socket) => {
console.log('A new user is connected !');
})
io.on('disconnect', () => {
console.log('User has left !');
});
另外,我在client (前端)中安装了socket.io-client,然后在我的网页中添加了以下代码:
import { io } from 'socket.io-client'
export default () => {
//implement socket
const socket = useRef()
useEffect(() => {
socket.current = io("ws://localhost/4000")
}, [])
return (
//some html code
)
}
项目论坛
├── back
├── client
└──index.jsx
└── socket
└──package.json
└──app.js
无恶魔启动‘节点apde app.js'
发布于 2022-08-28 12:12:36
const socketio = require("socket.io");
const express = require("express");
const http = require("http");
const app = express();
const PORT = process.env.PORT || 2018;
const server = http.createServer(app);
const io = socketio(server, {
cors: {
origin: "*",
methods: ["GET", "POST", "OPTIONS"]
}
});
server.listen(PORT, () => {
io.on("connection", socket => {
console.log("ok");
console.log(socket.id);
// io.in(roomID).emit()
socket.emit("WELCOME_MESSAGE", ` ${socket.id} welcome!! `);
});
});
https://stackoverflow.com/questions/71789359
复制相似问题