NodeJS Socket.io 内容安全政策:页面的设置被阻止错误

6tdlim6h  于 2023-01-01  发布在  Node.js
关注(0)|答案(1)|浏览(116)

我正在尝试用nodejs和express运行一个WebSocket服务器。服务器端代码是www.example.com文档中给出的简单代码示例Socket.io。

我使用的是最新版本的Socket.io(v4.5.4)

const app = express();

const httpServer = createServer(app);

const io = new Server(httpServer, {
  cors: {
    origin: "http://0.0.0.0:8000",
    credentials: true,
  },
  allowRequest: (req, callback) => {
    console.log("ALLOWING REQ");
    callback(null, true);
  },
  path: "/ws",
});

io.on("connection", () => {
  console.log("Connected");
});

app.listen(8000, () => {
  console.log(`server listening on http://0.0.0.0:8000`);
});

但是,当我试图通过浏览器连接到WebSocket,在控制台上键入以下内容:
第一个月
我收到此错误
Content Security Policy: The page’s settings blocked the loading of a resource at ws://0.0.0.0:8000/ws (“default-src”)
如果有帮助,这也是异常消息

Exception { name: "NS_ERROR_CONTENT_BLOCKED", message: "", result: 2153644038, filename: "debugger eval code", lineNumber: 1, columnNumber: 0, data: null, stack: "@debugger eval code:1:1\n" }

有谁能帮帮我我到底做错了什么?

uqcuzwp8

uqcuzwp81#

尝试下面的代码.它的工作很好,你可以设置允许的IP以及.

const app = express();

const httpServer = createServer(app);

let whitelist = ['*']
let corsOptions = {
  origin: function (origin, callback) {
    if (whitelist.indexOf(origin) !== -1 || whitelist.indexOf('*') !== -1) {
      callback(null, true)
    } else {
      callback(new Error('Not allowed by CORS'))
    }
  }
}
app.use("/", cors(corsOptions), index);

const io = require('socket.io')(httpServer, {
  cors: {
    origin: '*',
  }
});

io.on("connection", () => {
  console.log("Connected");
});

app.listen(8000, () => {
  console.log(`server listening on http://0.0.0.0:8000`);
});

相关问题