首页 > 解决方案 > (Nodejs + Angular 6 + socket.io) 中的 CORS 问题

问题描述

当我们尝试连接到服务器时,我们使用 socket.io 客户端在 Angular 6 中面临 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");
    });

标签: node.jssocketssocket.iocors

解决方案


根据您在上面给出的评论,我认为您应该以这样的方式使用 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
}

推荐阅读