【发布时间】:2021-05-17 03:56:24
【问题描述】:
我有一个在端口 4200 (http://localhost:4200) 上运行的本地 (Angular) 客户端和在端口 5000 (http://localhost:5000) 上运行的本地 (express) 服务器。每当我尝试连接到我的服务器时,都会收到此消息。
Access to XMLHttpRequest at 'http://localhost:5000/socket.io/?EIO=4&transport=polling&t=NU7H' from origin
'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
这是启动我的本地服务器的代码
@injectable()
export default class App {
app: express.Application;
constructor() {
this.app = express();
this.config();
this.bindRoutes();
}
// Middlewares config
private config(): void {
this.app.use(cors());
this.app.use(express.json());
this.app.use(express.urlencoded({ extended: true }));
}
bindRoutes(): void {
this.app.use('/', router);
}
}
这是我设置套接字的代码
private _ioServer: SocketIO.Server;
initSocket(server: http.Server) {
this._ioServer = new SocketIO.Server(server);
this.connectChat(); // Chat namespace
this.connectStream(); // Game board streaming namespace
}
我用 Postman 试过了,一切正常。
谢谢!
【问题讨论】:
标签: express socket.io cors localhost localserver