简体   繁体   English

使用 socket.io nodejs 处理 CORS 策略

[英]Struggling with CORS policy using socket.io nodejs

I have found a lot of information about the CORS policy problem, but nothing worked even when I have tried every solution I found here.我找到了很多关于 CORS 政策问题的信息,但即使我尝试了在这里找到的所有解决方案,也没有任何效果。

My last attempt was this in the nodejs server:我的最后一次尝试是在 nodejs 服务器中进行的:

var express = require('express');
var app = express();

var spawn = require('child_process').spawn;
var fs = require('fs');

app.use(express.static('public'));

const server = require('https').createServer({
    key: fs.readFileSync('/home/example/ssl/keys/c231f_0ca89_7b80bf6d84934d212df326eee9c6319f.key'),
    cert: fs.readFileSync('/home/example/ssl/certs/streaming_desytec_com_c231f_0ca89_1609334228_a73b63988075270c9f680f383b6e6a99.crt')
}, app);

var io = require('socket.io')(server);
io.set('origins', 'https://localhost:44356');

Despite my effort to solve this, I always get this error in the socket.io client:尽管我努力解决这个问题,但我总是在 socket.io 客户端中收到此错误:

Access to XMLHttpRequest at 'https://streaming.example.com/socket.io/?framespersecond=15&audioBitrate=22050&EIO=3&transport=polling&t=NJbfyAD' from origin 'https://localhost:44356' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

How can I really solve this?我怎样才能真正解决这个问题?

My website is in localhost and the nodejs server is running on a linux server remotely.我的网站在 localhost 中,nodejs 服务器远程运行在 linux 服务器上。

EDIT: I have this last attempt:编辑:我最后一次尝试:

var cors = require('cors')

var corsOptions = {
  origin: 'https://localhost:44356',
  optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204
}

app.use(cors());
app.get('/socket.io/', cors(corsOptions), function (req, res, next) {
  res.json({msg: 'This is CORS-enabled for all origins!'})
})

app.use(express.static('public'));

it still does not work.它仍然不起作用。 I am wondering if that app.get call I wrote is correct, considering that the URL of the server will be:我想知道我写的那个app.get调用是否正确,考虑到服务器的 URL 将是:

/socket.io/?framespersecond=15&audioBitrate=22050&EIO=3&transport=polling&t=NJbfyAD

yourapp.use(
  cors({
    origin: (origin, callback) => callback(null, true),
    credentials: true // if using cookies
  })
);

You can control it based on your environment.您可以根据您的环境来控制它。

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

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