Node js + Angular 应用程序中的 Socket io 通信被 CORS 策略阻止

Paz*_*azu -1 node.js cors socket.io angular

因此,我使用带有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/'));

io.on('connection', socket => {
    socket.emit('connection', 'data from server!');
});
 
http.listen(port, () => {
    console.log('App listening on port ' + port);
});
Run Code Online (Sandbox Code Playgroud)

使用套接字 io 的类:

import { SocketIoModule, SocketIoConfig } from 'ngx-socket-io';

const hostname = window.location.hostname;
const url = (hostname === 'localhost') ? `${window.location.protocol}//${hostname}:5000` : undefined;
const config: SocketIoConfig = { url, options: {} };

@NgModule({
  declarations: [...],
  imports: [
    ...
    SocketIoModule.forRoot(config)
Run Code Online (Sandbox Code Playgroud)

我尝试使用服务器端的标头修复 CORS 错误,例如:

constructor(private socket: Socket) { }

    this.socket.on('connection', (data) => {
      console.log('Working ' + data);
    });

Run Code Online (Sandbox Code Playgroud)

或者

const io = require('socket.io')(server, {
  cors: {
    origin: '*',
  }
});
Run Code Online (Sandbox Code Playgroud)

但它仍然显示相同的错误。

我当然使用该命令ng serve来运行我的应用程序(在端口 4200 上运行),并且它在 3 个月前运行良好。(与 ngserve 以及 ng build prod 一起使用)。

Wal*_*dia 5

验证角度packaje.json文件上的 socket.io-client 版本。如果它低于 3.1.2,您可以尝试通过以下方式升级它 npm install socket.io-client@3.1.2 --save 您也可以再次验证服务器端查看此

const app = require('express')();
const http = require('http').createServer(app);
const io = require('socket.io')(http, {
    cors: {
        origins: ['http://localhost:4200']
    }
});
Run Code Online (Sandbox Code Playgroud)

替换http://localhost:4200为 Angular 应用程序上您当前的环境