我试图连接到一个唯一的api但是没有工作,给我一个错误:
XMLHttpRequest cannot load https://api.sports/socket.io/?api_key=aredasdasdadds&EIO=3&transport=polling&t=LsYSPsv. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8000' is therefore not allowed access. The response had HTTP status code 596.
奇怪的是错误显示了不同的api url。
我的代码是:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<h1>Web socket</h1>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.3/socket.io.js"></script>
<script type="text/javascript">
// Create SocketIO instance, connect
var socket = new io('https://api.sports.com/soccer-/eu/en/matches/summary.json?api_key=aredasdasdadds');
socket.connect();
// Add a connect listener
socket.on('connect',function() {
console.log('Client has connected to the server!');
});
// Add a connect listener
socket.on('message',function(data) {
console.log('Received a message from the server!',data);
});
// Sends a message to the server via sockets
function sendMessageToServer(message) {
socket.send(message);
}
</script>
</body>
</html>
答案 0 :(得分:0)
你的服务器是什么?
首先,你必须检查socket.io的版本在客户端和服务器上是否相同(我在客户端看到的是2.0.3)。
其次,您只需要使用您的网站域名:
var socket = io.connect('ws://https://api.sports.com:8443/', {transports: ['websocket']});
将端口设置为listen,通常为8443表示https。
问候!