【问题标题】:CORS error when running node.js and socket.io in firefox在 Firefox 中运行 node.js 和 socket.io 时出现 CORS 错误
【发布时间】:2015-06-24 02:10:35
【问题描述】:

我在 apache 上运行带有 socket.io 的 node.js。我让它在子域上运行(例如 - myapp.mydomain.com:8000),你可以看到我在不同的端口上运行它,以便我可以使用 myapp.mydomain.com 访问它。

在 chrome、Opera、IE 中一切正常,但 FF 失败并且出现跨域错误。

跨域请求被阻止:同源策略不允许读取位于http://myapp.mydomain.com:8000/socket.io/?EIO=2&transport=polling&t=1429260923523-0 的远程资源。这可以通过将资源移动到同一域或启用 CORS 来解决。

有什么想法吗?

更新:

按要求添加了我的代码:

function handler(req, res) {
  fs.readFile('../index.html', function(err, data) {
    if (err) {
      console.log(err);
      res.writeHead(500);
      return res.end('Error loading client.html');
    }
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    res.writeHead(200);
    res.end(data);
  });
}

【问题讨论】:

  • 您是否设置了任何 CORS 标头?如果是这样,您可以将它们添加到您的问题中吗?
  • 您不能拥有Access-Control-Allow-Headers 两次。应该是res.header("Access-Control-Allow-Headers", "X-Requested-With, Content-Type");。
  • 检查并按照建议进行。还是不开心!

标签: javascript node.js sockets firefox


【解决方案1】:

Websockets (Socket.IO) 不依赖于 CORS。 Socket.IO 背后的主要原因之一是在处理不同域时完全停止 CORS 类型的问题。如果您认为这可以通过启用 cors 来完成,那么假设您使用的是 express.js 或 hapi.js,请尝试此操作,请参阅这链接到如何启用 cors。

hapijs -->

new Hapi.Server({
  connections: {
    routes: {
      cors: true
    }
  }
})

expressjs -->

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

【讨论】:

  • 得到这个东西是为了快递。 Chrome 没问题,firefox 还是有问题
猜你喜欢
  • 2018-06-29
  • 2019-06-03
  • 2012-02-10
  • 2019-11-09
  • 1970-01-01
  • 2021-10-07
  • 2017-11-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多