Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/34.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js CORS问题(Nodejs+;Angular 6+;socket.io)_Node.js_Sockets_Socket.io_Cors - Fatal编程技术网

Node.js CORS问题(Nodejs+;Angular 6+;socket.io)

Node.js CORS问题(Nodejs+;Angular 6+;socket.io),node.js,sockets,socket.io,cors,Node.js,Sockets,Socket.io,Cors,在Angular 6中,当我们尝试连接到服务器时,我们使用socket.io客户端面临CORS问题 浏览器控制台中出现的错误 Access to XMLHttpRequest at 'http://********.com/socket.io/?EIO=3&transport=polling&t=N3jTiAZ' from origin 'http://localhost:4200' has been blocked by CORS policy: The value of

在Angular 6中,当我们尝试连接到服务器时,我们使用socket.io客户端面临CORS问题

浏览器控制台中出现的错误

Access to XMLHttpRequest at 'http://********.com/socket.io/?EIO=3&transport=polling&t=N3jTiAZ' from origin 'http://localhost:4200' has been blocked by CORS policy: 

The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'.

 The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
这是服务器代码

const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const server = require('http').createServer(app);
const conn = app.listen("3000")
const io = require('socket.io').listen(conn);

io.origins('*:*') 

var connectioncheck = io.of('/check-connection');
connectioncheck.on('connection', function (socket) {
   console.log('user  connected');
});
下面是使用简单html和js的前端代码

   <script src="https://cdn.jsdelivr.net/npm/socket.io-client@2/dist/socket.io.js"></script>
var socket = io.connect('http://********.com/check-connection');
socket.emit('connection', "hello",function(db){
        console.log(db);
        console.log("data from callback");
    });

var socket=io.connect('http://*********.com/check connection');
emit('connection','hello',函数(db){
控制台日志(db);
log(“来自回调的数据”);
});

根据您在上面给出的评论,我认为您应该以如下方式使用NPM CORS


你试过npm使用cors吗?是的,我尝试了,但没有成功访问位于“http://******.com/socket.io/?EIO=3&transport=polling&t=N3jY9aF”“from origin”“的XMLHttpRequest已被CORS策略阻止:“Access Control Allow origin”标头包含多个值“*,”,但只允许一个值。当我尝试CORS时,我明白了这一点。我认为你应该以这里所述的方式使用NPM CORS。我尝试了它,但没有使用任何其他解决方案
let allowedOrigins = ["http://ServerA:3000", "http://ServerB:3000"]
let origin = req.headers.origin;
if (allowedOrigins.includes(origin)) {
  res.header("Access-Control-Allow-Origin", origin); // restrict it to the required domain
}