套接字io CORS被阻止

时间:2019-03-22 03:28:55

标签: socket.io

在使用https域和https套接字io时收到此警告。

---
layout: page
title: References
permalink: /documents/
---
<h1>References table</h1>

{% assign big_subject = "" | split: "" %}
{% assign middle_subject = "" | split: "" %}

{% for post in site.posts %}
  {% assign big_subject= big_subject | concat: post.big-title %}
  {% assign middle_subject= middle_subject | concat: post.middle-title %}
{% endfor %}

我的代码是这样的:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://iosocket.transys.id:30005/socket.io/?EIO=3&transport=polling&t=McZQ-hN. (Reason: CORS request did not succeed).

想要解决这个问题。我已经从别人那里搜索了,申请后不起作用。

2 个答案:

答案 0 :(得分:0)

使用此代码进行工作。

app.use(
  cors({
    origin: 'http://localhost:3000', // allow to server to accept request from different origin
    methods: 'GET,HEAD,PUT,PATCH,POST,DELETE',
    credentials: true // allow session cookie from browser to pass through
  })
);

答案 1 :(得分:0)

取决于项目的情况,这可能不是您所需要的。但是无论如何,我写这可能对某人有帮助。我本人想从使用php渲染的脚本连接到Socket.IO + NodeJS


完整的两端工作代码都可以这样

服务器

let pth = require('path');
let exp = require('express');
let app = exp();

//UPDATE: this is seems to be deprecated
//let io = require('socket.io').listen(app.listen(9009));
//New Syntax:
let io = require('socket.io')(app.listen(9009));

app.all('/', function (q, p, next) {
    p.header("Access-Control-Allow-Origin", "*");
    p.header("Access-Control-Allow-Headers", "X-Requested-With");
    next();
});

io.on('connection', (socket) => {
    console.log("connected");
    socket.on('msg', (msg) => {
        console.log(msg);
        io.emit('msg', msg);
    });
});

客户端(在我的情况下是php脚本):

<head>
    <script src="http://127.0.0.1:9009/socket.io/socket.io.js"></script>
    <script>
        let $$ = (id) => {return document.getElementById(id);};

        var socket = io("127.0.0.1:9009/", {
            "force new connection": true,
            "reconnectionAttempts": "Infinity", 
            "timeout": 10001, 
            "transports": ["websocket"]
        });

        socket.on('msg', (msg) => {$$("holder").innerHTML += msg;});

        let emit = (_msg) => {socket.emit("msg", _msg);};
    </script>
</head>
<body>
    <?php echo "php echo ...";?>

    <div onclick="socket.emit('msg','my msg');">BUTTON</div>
    <div id="holder">Chat ...</div>
</body>