【发布时间】:2022-01-11 22:09:39
【问题描述】:
所以,我正在尝试按照this 教程进行操作,但我无法立即使用它。 首先,这些是我的文件:
root/frontend/index.html
<html>
[...]some static page[...]
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.3.0/socket.io.js"></script>
<script src="index.js"></script>
</html>
root/frontend/index.js
const socket=io('http://localhost:3000');
socket.on('init', handleInit);
function handleInit(msg) {
console.log(msg);
}
root/server/server.js
const io=require('socket.io')();
io.on('connection', client =>{
client.emit('init', {data:'hello'});
});
io.listen(3000);
他接下来要做的是在前端文件夹中运行“npx live-server”(我也这样做)。此外,在服务器文件夹中运行“yarn add socket.io”,然后运行“npx nodemon server.js”,它应该可以工作。但是做这些确切的步骤我得到了错误: “跨域请求被阻止:同源策略不允许在 http://localhost:3000/socket.io/?EIO=3&transport=polling&t=NsGvIgN 读取远程资源。(原因:CORS 请求未成功)”
和
“GET http://localhost:3000/socket.io/?EIO=3&transport=polling&t=NsGvO1Z”
【问题讨论】:
标签: javascript node.js socket.io