【问题标题】:How to fix this CORS issue in socket.io?如何在 socket.io 中解决这个 CORS 问题?
【发布时间】:2021-04-10 11:16:04
【问题描述】:

我正在尝试使用 socket.io 连接到远程服务器,但我遇到了一些问题。我收到此错误:响应中 Access-Control-Allow-Credentials 标头的值是“”,当请求的凭据模式为“包含”时,它必须为“真”

好的,代码如下:

服务器

var server = require('http').createServer();

const io = require("socket.io")(server, {
  cors: {
    origin: "my URL",
    methods: ["GET", "POST"],
    credentials: false
  }
});


io.sockets.on('connection', function(socket) {
    console.log("Client has connected!");
});

console.log ('Server started.');
server.listen(3000);

这是客户端代码:

var socket = io.connect("https://persistent-gentle-banon.glitch.me", {
  withCredentials: false
});

我怎样才能解决这个问题并让它连接?

感谢您的帮助!

【问题讨论】:

    标签: javascript node.js socket.io


    【解决方案1】:

    根据此链接https://socket.io/docs/v4/server-instance/#serverengine,您应该使用 io.engine initial_headersheaders 事件来简单地设置 cors 标头,这应该适用于 socket.io v4+。

    import { createServer } from "http";
    import {Server} from  'socket.io';
    
    const server = createServer(app);
    const io = new Server(server);
    
    io.engine.on("initial_headers", (headers, req) => {
      headers["Access-Control-Allow-Origin"] = "http://localhost:4200";
    });
    
    io.engine.on("headers", (headers, req) => {
      headers["Access-Control-Allow-Origin"] = "http://localhost:4200"; // url to all
    });
    
    server.listen(3000);
    

    【讨论】:

      【解决方案2】:

      我遇到了同样的问题,我用的是快递,我能够解决它

      var cors = require("cors");
      const corsOptions = {
        origin: "*",
        optionsSuccessStatus: 200
      };
      const io = require("socket.io")(server, {
        cors: {
          origin: "*",
          methods: ["PUT", "GET", "POST", "DELETE", "OPTIONS"],
          credentials: false
        }
        // transports: ['websocket']
      });
      
      app.use(cors(corsOptions));
      

      【讨论】:

      • 我是否保持客户端的代码相同?还有你注释掉的那一行是什么?
      • 是的,它可以是一样的
      • 嗯.....它似乎不起作用。也许你错过了一些代码?
      猜你喜欢
      • 2011-06-10
      • 1970-01-01
      • 2020-08-06
      • 2014-10-07
      • 1970-01-01
      • 2016-01-24
      • 2011-09-19
      相关资源
      最近更新 更多