问题描述
我尝试在Angular和Nodejs服务器之间连接socket.io
I trying to connect socket.io between Angular and Nodejs Server
在Angular中我声明了一个新的套接字并将它连接起来
import * as io from socket.io客户端;
...
@component
...
const socket = io.connect('');
In Angular I have declared a new socket and connect it import * as io from 'socket.io-client'; ... @component ... const socket = io.connect('http://localhost:3000');
在后端:server.js
In back end : 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不工作
我收到此错误:
The app is compiling and getting data from server. but only socket.io is not workingI get this error:
为什么即使在服务器端配置CORS后错误仍然存在?
Why is error persist even after configuring CORS in server side ?
推荐答案
消息很清楚:
这是因为你正在设置属性 withCredentials
XMLHttpRequest
到 true
。因此,您需要删除通配符,并添加 Access-Control-Allow-Credentials
标题。
This happens because you're setting the property withCredentials
on your XMLHttpRequest
to true
. So you need to drop the wildcard, and add Access-Control-Allow-Credentials
header.
res.header("Access-Control-Allow-Origin", "http://localhost:4200");
res.header('Access-Control-Allow-Credentials', true);
您可以使用包,轻松实现白名单:
You can use cors package, to easily implement a whitelist:
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));
这篇关于当请求的凭据模式为“include”时,响应中“Access-Control-Allow-Origin”标头的值不能是通配符“*”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!