簡體   English   中英

"對使用 NESTJS 啟用 CORS 沒有影響"

[英]no affect on CORS enabling with 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();

如果我們接受所有域,請不要告訴我 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.

在 chrome 標頭檢查中,我看到:

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-

Referrer Policy: strict-origin-when-cross-origin有影響嗎?

(順便說一句,通過簡單的快速設置它就可以正常工作。所以這不是我的瀏覽器的錯。)

enableCors{ cors: true }選項用於 HTTP 服務器(express 或 fastify)。 給出的顯示 CORS 錯誤的 URL 來自 socket.io 連接。 要為socket.io啟用 CORS,您需要使用@WebsocketGateway()裝飾器中的選項,例如

@WebsocketGateway({ cors: '*:*' })
export class FooGateway {}

確保將 websocket cors 的主機和端口都設置為host:port

我最近有同樣的問題
並在 main.ts 中將其修復為以下內容

in main.ts

    // import
    import { NestExpressApplication } from '@nestjs/platform-express';

    //in bootstrap() function
    const app = await NestFactory.create<NestExpressApplication>(AppModule);
    app.enableCors();
    app.setGlobalPrefix('/api/v1')

我刪除或更改了數組中的傳輸參數。 它來自前端

    //FRONTEND FILE
    socket = io(BE_URL, {
      withCredentials: true,
      query: {
        token,
        isUserNew,
      },
      transports: ['websocket', 'polling'], // USE ['polling', 'websocket'] OR DELETED IT
      autoConnect: false,
    });



//BACKEND FILE
@WebSocketGateway({
  cors: { credentials: true, methods: ['GET', 'POST'], origin: ['http://host1', 'http://host2']},
  transports: ['polling', 'websocket'],
})

我讀了 - https://socket.io/docs/v3/client-initialization/#transports

一個可能的缺點是,只有在 WebSocket 連接建立失敗時才會檢查 CORS 配置的有效性。

我真的希望這個答案可以為您節省一些時間。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM