当请求的凭据模式为“ include”时,响应中“ Access-Control-Allow-Origin”标头的值不得为通配符“ *”

Ham*_*dad -1 javascript node.js cors socket.io angular

我试图在Angular和Nodejs服务器之间连接socket.io

在Angular中,我声明了一个新套接字,并从'socket.io-client'中将其导入为io *。... @component ... const socket = io.connect(' http:// localhost:3000 ');

在后端:server.js

const express = require('express');
const app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
io.set('origins', 'http://localhost:4200');

var routes = require('./routes/routes')(io);

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Methods", "GET, POST, PUT ,DELETE");
    res.header(
        "Access-Control-Allow-Headers",
        "Origin, X-Requested-With, Content-Type, Accept"
    );
    next();
});
io.on('connection', function (socket) {
    socket.emit('news', { hello: 'world' });
    console.log("connectd");
});
app.use('/', routes);
var server = app.listen(3000, function (io) {
})
Run Code Online (Sandbox Code Playgroud)

该应用正在编译并从服务器获取数据。但只有socket.io无法正常工作,我收到此错误:

localhost /:1无法加载http:// localhost:3000 / socket.io /?EIO = 3&transport = polling&t = MEpHAtN:响应中“ Access-Control-Allow-Origin”标头的值不能为通配符当请求的凭据模式为“包括”时为“ *”。因此,不允许访问源' http:// localhost:4200 '。XMLHttpRequest发起的请求的凭据模式由withCredentials属性控制。

为什么即使在服务器端配置了CORS,错误仍然存​​在?

mrt*_*rsn 16

对于简单的无安全性的 socket.io (v.4) 服务器配置,请尝试:

const ios = require('socket.io');
const io = new ios.Server({
    allowEIO3: true,
    cors: {
        origin: true,
        credentials: true
    },
})
io.listen(3000, () => {
    console.log('[socket.io] listening on port 3000')
})
Run Code Online (Sandbox Code Playgroud)

allowEIO3仅当您希望与旧版 socket.io 客户端兼容时才需要)


Mar*_*nde 6

消息很清楚:

当请求的凭据模式为“ include 时,响应中 “ Access-Control-Allow-Origin” 标头的值不得为通配符“ *”

这是因为你设置该属性withCredentials对你XMLHttpRequesttrue。因此,您需要删除通配符,并添加Access-Control-Allow-Credentials标题。

res.header("Access-Control-Allow-Origin", "http://localhost:4200");
res.header('Access-Control-Allow-Credentials', true);
Run Code Online (Sandbox Code Playgroud)

您可以使用cors软件包轻松实现白名单:

const cors = require('cors');
const whitelist = ['http://localhost:4200', 'http://example2.com'];
const corsOptions = {
  credentials: true, // This is important.
  origin: (origin, callback) => {
    if(whitelist.includes(origin))
      return callback(null, true)

      callback(new Error('Not allowed by CORS'));
  }
}

app.use(cors(corsOptions));
Run Code Online (Sandbox Code Playgroud)

  • 很好,现在唯一的错误是 `zone.js:2969 GET http://localhost:3000/socket.io/?EIO=3&transport=polling&t=MEpLcDy 404 (Not Found)` (2认同)