因此,我使用带有express和socket.io的简单node.js服务器当我尝试与用javascript编写的简单客户端通信时,它工作得很好,但是当我尝试与Angular应用程序创建通信时(使用ngx-socket- io),我收到以下错误消息:
Access to XMLHttpRequest at 'http://localhost:5000/socket.io/?EIO=3&transport=polling&t=NQFEnVV' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Run Code Online (Sandbox Code Playgroud)
这是nodejs服务器:
Access to XMLHttpRequest at 'http://localhost:5000/socket.io/?EIO=3&transport=polling&t=NQFEnVV' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Run Code Online (Sandbox Code Playgroud)
这就是我在 Angular 客户端上实现 socket.io 的方式:
应用程序模块.ts:
var express = require('express');
var app = express();
const http = require('http').Server(app);
const io = require('socket.io')(http);
const port = process.env.PORT || 5000;
app.set(port, process.env.PORT);
app.use(express.static('./client/')); …Run Code Online (Sandbox Code Playgroud)