socket.io, 'Access-Control-Allow-Origin' 错误 [英] socket.io, 'Access-Control-Allow-Origin' error

查看:36
本文介绍了socket.io, 'Access-Control-Allow-Origin' 错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经设置了一个带有 socket io 转向的节点服务器,并试图通过另一台服务器连接到它.但是,不同计算机上的某些浏览器会出现此错误并使其始终重新连接:

I have set up a node server with socket io turning and trying to connect to it through another server. However some browsers on different computers give me this error and makes it reconnect the whole time:

XMLHttpRequest 无法加载 https://serverDomain.net:3000/socket.io/?EIO=3&transport=polling&t=Lo_SdiU.当请求的凭据模式为包含"时,响应中Access-Control-Allow-Origin"标头的值不能是通配符*".因此,不允许访问源 'https://www.differentServerDomain.fr'.XMLHttpRequest 发起的请求的凭证模式由 withCredentials 属性控制.

XMLHttpRequest cannot load https://serverDomain.net:3000/socket.io/?EIO=3&transport=polling&t=Lo_SdiU. The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. Origin 'https://www.differentServerDomain.fr' is therefore not allowed access. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

我的 js 配置:

var port = 3000;
var fs = require('fs');
var https = require('https');
var express = require('express');
var app = express();

var options = {
    key: fs.readFileSync('/etc/letsencrypt/live/devpeter.net/privkey.pem'),
    cert: fs.readFileSync('/etc/letsencrypt/live/devpeter.net/fullchain.pem')
};
var server = https.createServer(options, app);
var io = require('socket.io')(server);
io.origins('https://www.differentServerDomain.fr:* https://www.differentServerDomain.fr/wp-admin/index.php:*');

// start of server
server.listen(port, function(){
    console.log('listening on *: '+ port + "
");
});

我使用的是 node 8.0 和 socket io 2.2,您的帮助将不胜感激.

I am using node 8.0 and socket io 2.2, Your help will be greatly appreciated.

这是客户端代码:

<script src="https://serverDomain.net:3000/socket.io/socket.io.js"></script>
<script>
   var socket = io('https://serverDomain.net:3000');
</script>

推荐答案

我找到了解决方案.出于某种原因,并非所有服务器都允许使用默认的传输方式.

I have found a solution. for some reason the default transportation method is not always allowed by all servers.

所以我在客户端指定了一个中立的传输方法,如下所示:

So i specified a neutral transportation method at the client side, like this:

var socket = io('https://yourDomain:3000', { transports : ['websocket'] });

这篇关于socket.io, 'Access-Control-Allow-Origin' 错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆