对使用 NESTJS 启用 CORS 没有影响

fed*_*der 3 websocket node.js nestjs

我无法启用 CORS 来使用最新的 NestJS 8.0.6 和新的 http + ws 项目进行测试。也就是说,我想看到 Access-Control-Allow-Origin服务器响应(以便客户端接受它)。这是我的 main.ts,我尝试了 3 种方法:1)使用选项,2)使用方法,3)使用 app.use。它们都不起作用。

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { microserviceConfig} from "./msKafkaConfig";

async function bootstrap() {
  const app = await NestFactory.create(AppModule, { cors: true}); // DOESN'T WORK
  app.enableCors(); // DOESN'T WORK

  app.connectMicroservice(microserviceConfig);
  await app.startAllMicroservices();

  
  // DOESN'T WORK
  app.use((req, res, next) => {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,PATCH,OPTIONS,UPGRADE,CONNECT,TRACE');
    res.header('Access-Control-Allow-Headers', 'Content-Type, Accept');
    next();
  });
  
  await app.listen(3000);



}
bootstrap();
Run Code Online (Sandbox Code Playgroud)

请不要给我上一课,告诉我如果我们接受所有域名,CORS (XSForgery) 会有多么危险。关于这一点有足够的材料。我很清楚这一点。这是关于 NestJS 不回复Access-Control-Allow-Origin标头中的元素。

浏览器控制台报告:

Access to XMLHttpRequest at 'http://localhost:3000/socket.io/?EIO=4&transport=polling&t=Nm4kVQ1' 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)

在镀铬标头检查中我看到:

Request URL: http://localhost:3000/socket.io/?EIO=4&transport=polling&t=Nm4kUZ-
Referrer Policy: strict-origin-when-cross-origin
Connection: keep-alive
Content-Length: 97
Content-Type: text/plain; charset=UTF-8
Date: Mon, 20 Sep 2021 19:41:05 GMT
Keep-Alive: timeout=5
Accept: */*
Accept-Encoding: gzip, deflate, br
Accept-Language: en,de-DE;q=0.9,de;q=0.8,en-US;q=0.7,es;q=0.6
Cache-Control: no-cache
Connection: keep-alive
Host: localhost:3000
Origin: http://localhost:4200
Pragma: no-cache
Referer: http://localhost:4200/
sec-ch-ua: "Google Chrome";v="93", " Not;A Brand";v="99", "Chromium";v="93"
sec-ch-ua-mobile: ?0
sec-ch-ua-platform: "Windows"
Sec-Fetch-Dest: empty
Sec-Fetch-Mode: cors
Sec-Fetch-Site: same-site
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.82 Safari/537.36
EIO: 4
transport: polling
t: Nm4kUZ-
Run Code Online (Sandbox Code Playgroud)

Referrer Policy: strict-origin-when-cross-origin有影响吗?

(顺便说一句,它通过简单的快速设置就可以正常工作。所以这不可能是我的浏览器的错。)

Jay*_*iel 10

enableCors选项{ cors: true }适用于 HTTP 服务器(express 或 fastify)。显示 CORS 错误的 URL 来自 socket.io 连接。要启用 CORS,socket.io您需要使用装饰器中的选项@WebsocketGateway(),例如

@WebsocketGateway({ cors: '*:*' })
export class FooGateway {}
Run Code Online (Sandbox Code Playgroud)

确保将 websocket cors 的主机和端口设置为host:port