【问题标题】:CORS issue in (Nodejs + Angular 6 + socket.io)(Nodejs + Angular 6 + socket.io) 中的 CORS 问题
【发布时间】:2020-06-29 12:30:03
【问题描述】:

当我们尝试连接到服务器时,我们在使用 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");
    });

【问题讨论】:

  • 你试过用 npm 的 cors 吗? npmjs.com/package/cors
  • 是的,我试过了,但没用
  • 从源“localhost:4200”访问“http://******.com/socket.io/?EIO=3&transport=polling&t=N3jY9aF”的 XMLHttpRequest 已被阻止CORS 策略:“Access-Control-Allow-Origin”标头包含多个值“*,localhost:4200”,但只允许一个。当我尝试 cors 时,我得到了这个
  • 我认为您应该按照此处stackoverflow.com/questions/41910130/… 中所述的方式使用 NPM CORS
  • 我尝试过,但没有任何其他解决方案

标签: node.js sockets socket.io cors


【解决方案1】:

根据您在上面给出的 cmets,我认为您应该以 this 之类的方式使用 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
}

【讨论】:

    猜你喜欢
    • 2021-05-09
    • 2019-06-04
    • 2018-12-30
    • 1970-01-01
    • 2020-05-29
    • 1970-01-01
    • 2021-12-11
    • 1970-01-01
    • 2017-04-19
    相关资源
    最近更新 更多