我尝试在Angular和Nodejs Server之间连接socket.io
在Angular中,我声明了一个新的套接字,并将它连接到import * as io from 'socket.io-client';... @component ...const套接字= 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) {
})应用程序正在编译并从服务器获取数据。但是只有socket.io没有工作,我得到了这个错误:
localhost/:1未能加载http://localhost:3000/socket.io/?EIO=3&transport=polling&t=MEpHAtN:当请求的凭据模式为“”include“”时,响应中的“”Access-Control-Allow-http://localhost:3000/socket.io/?EIO=3&transport=polling&t=MEpHAtN“”标头的值不能是通配符“”*“”。“”因此不允许访问源'http://localhost:4200‘。由withCredentials属性控制XMLHttpRequest发起的请求的凭据模式。
为什么在服务端配置CORS后仍然出错?
发布于 2018-05-31 07:05:50
这条信息很清楚:
当请求的凭据模式为‘
’时,响应中的'Access-Control-Allow-Origin‘标头的值不能是通配符'*'
这是因为您将XMLHttpRequest上的属性withCredentials设置为true。所以你需要去掉通配符,然后添加Access-Control-Allow-Credentials报头。
res.header("Access-Control-Allow-Origin", "http://localhost:4200");
res.header('Access-Control-Allow-Credentials', true);您可以使用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));发布于 2021-06-21 15:32:40
对于简单的无安全性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')
})(仅当您希望与较旧的socket.io客户端兼容时,才需要allowEIO3)
https://stackoverflow.com/questions/50614397
复制相似问题