You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

远程HTML连接本地socket.io@2.2.0服务器遇CORS问题求助

解决远程HTTP页面连接本地Socket.io@2.2.0的CORS问题

我们有一套旧系统,HTML托管在远程HTTP服务器,需要连接本地部署的socket.io@2.2.0服务器(因服务器需本地部署,自签名SSL效果不佳)。之前通过禁用Chrome的Block insecure private network requests标志(chrome://flags/#block-insecure-private-network-requests)解决跨域问题,但该标志现已移除,现在出现CORS错误:

Access to XMLHttpRequest at 'http://localhost/socket.io/?EIO=3&transport=polling&t=OLTDEpr' from origin 'http://remote.com' has been blocked by CORS policy: The request client is not a secure context and the resource is in more-private address space `local`.

尝试过Stack Overflow相关跨域方案但无效,已将系统简化到最基础形式仍未找到解决方案,相关代码如下:

本地Socket.io服务器代码

const express = require('express');
const app = express();
const http = require('http').Server(app);
const io = require("socket.io")(http);
io.origins('*:*');

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();
});

io.on("connection", function(socket){
    console.log("A new connected, with socketid " + socket.id);
});

http.listen(80, function(){
    console.log("start");
});

远程服务器代码

const express = require('express');
const app = express();
const http = require('http').Server(app);

app.use(express.static('public'));
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');

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();
});

app.get('/*', function(req, res){
    res.render('home');
});

http.listen(80, function(){
    console.log("Server started");
});

远程HTML页面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="./js/site.js"></script>
</head>
<body>
    
    <script>
        Test.Init("http://localhost");
    </script>
</body>
</html>

远程JS文件

/*!
 * Socket.IO v2.1.0
 * (c) 2014-2018 Guillermo Rauch
 * Released under the MIT License.
 */
// 此处包含Socket.IO客户端代码

const Test = function(){

    const Init = (url) => {
        const socket = io(url);
        socket.on('connect', function(){
            console.log("Successfully connected!");
        });
    }

    return {
        Init
    }
}();

内容的提问来源于stack exchange,提问作者Nick

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 20:20:36