【问题标题】:Cant connect to a external server (api) in socket io无法连接到套接字 io 中的外部服务器(api)
【发布时间】:2017-08-18 00:10:26
【问题描述】:

我试图连接到一个唯一的 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>

【问题讨论】:

  • 该 URL 看起来不像是 Socket.IO 端点。您是否尝试检索该 URL?如果是这样,请使用fetch

标签: javascript node.js websocket socket.io


【解决方案1】:

你的服务器是什么?

首先,您必须检查客户端和服务器上的socket.io版本是否相同(我看到客户端是2.0.3)。

其次,您只需要像这样使用您的网站的域:

  var socket = io.connect('ws://https://api.sports.com:8443/', {transports: ['websocket']});  

并且设置监听的端口,一般是8443对于https。

问候!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-25
    • 2022-09-28
    • 2021-04-19
    • 1970-01-01
    • 2023-02-08
    • 1970-01-01
    相关资源
    最近更新 更多