【问题标题】:404 not found when using socket.io-client with react使用带有反应的 socket.io-client 时找不到 404
【发布时间】:2017-12-29 19:36:50
【问题描述】:

我正在我的 react 应用程序中实现 socket.io-client package。我的反应应用程序正在使用 express 和 webpack。使用以下代码时:

import io from 'socket.io-client';

const socket = io('http://localhost');

在任何组件中,我都会收到以下错误:

polling-xhr.js:264 POST http://localhost/socket.io/?EIO=3&transport=polling&t=Lrprs_y 404(未找到)

使用http://localhost:80时出现同样的错误。

当在'localhost`的地方使用127.0.0.1时,它会抛出以下错误:

XMLHttpRequest 无法加载 http://127.0.0.1/socket.io/?EIO=3&transport=polling&t=Lrq3G9W。请求的资源上不存在“Access-Control-Allow-Origin”标头。 Origin 'http://localhost' 因此不允许访问。

【问题讨论】:

  • 尝试指定应用程序运行的端口,如io('http://localhost:8080'),并确保服务器正在运行
  • @ShubhamKhatri 默认运行80。使用io('http://localhost:80') 时仍然出现同样的错误。当使用 127.0.0.1 而不是 localhost 时,它会抛出 CORS 错误

标签: reactjs socket.io


【解决方案1】:

我认为您需要做的就是将您的代码放入componentDidMount。做这样的事情:

// Client
componentDidMount() {
    const socket = io('http://localhost:8000');
    socket.on('message', message => {
      console.log(message);
    });
}

// Server
const io = require('socket.io')();

io.on('connection', (client) => {
   console.log('a user connected:', client);
});
io.listen(8000);
console.log('socket io is listening on port ', 8000);
setInterval(() => {
  io.send('hello world');
}, 1000);

然后运行 ​​npm run build 和 npm run prod (或任何你的命令来启动节点 js 服务器)。 附言您还可以将 express 与套接字 io 一起使用

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-26
    • 1970-01-01
    • 1970-01-01
    • 2017-12-08
    • 2018-12-12
    相关资源
    最近更新 更多