简体   繁体   English

如何在 socket.io 中修复此 CORS 问题?

[英]How to fix this CORS issue in socket.io?

I am trying to connect to a remote server with socket.io, but I am having some problems.我正在尝试使用 socket.io 连接到远程服务器,但我遇到了一些问题。 I am getting this error: The value of the Access-Control-Allow-Credentials header in the response is ' ' which must be 'true' when the request's credentials mode is 'include'我收到此错误:响应中的Access-Control-Allow-Credentials header 的值为“”,当请求的凭据模式为“包含”时,它必须为“真”

OK, so here is the code:好的,下面是代码:

Server服务器

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

Here is the client code:这是客户端代码:

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

How can I solve this and get it to connect?我该如何解决这个问题并让它连接?

Thanks for any help!谢谢你的帮助!

i had the same problem, i was using express and i was able to solve it by我有同样的问题,我正在使用快递,我能够通过

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

According to this link https://socket.io/docs/v4/server-instance/#serverengine , you should use io.engine initial_headers and headers events to set cors headers simply, this should work with socket.io v4+. According to this link https://socket.io/docs/v4/server-instance/#serverengine , you should use io.engine initial_headers and headers events to set cors headers simply, this should work with 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM