当前位置: 首页 > 知识库问答 >
问题:

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

唐炜
2023-03-14
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) {
})

该应用程序正在编译和从服务器获取数据。但是只有socket.io不工作,我得到以下错误:

localhost/:1未能加载http://localhost:3000/socket.io/?eio=3&transport=polling&t=mephatn:当请求的凭据模式为“include”时,响应中“access-control-allog-origin”标头的值不能是通配符“*”。因此,不允许访问源'http://localhost:4200'。由XMLHttpRequest发起的请求的凭据模式由withCredentials属性控制。

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

共有1个答案

鱼浩荡
2023-03-14

信息足够明确:

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

发生这种情况是因为您将XMLHttpRequest上的With Credentials属性设置为True。因此,您需要删除通配符,并添加access-control-allog-credentials标头。

res.header("Access-Control-Allow-Origin", "http://localhost:4200");
res.header('Access-Control-Allow-Credentials', true);
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));
 类似资料: