azure - CORS:Azure WebApp Docker 容器内的 NestJs,CORS 被拒绝

标签 azure cors azure-web-app-service nestjs

我目前正在尝试在 Azure WebApp Docker 容器上部署我的 NestJs 应用程序。

当我的前端(部署在 azure 上)访问后端 api 时,我收到 CORS 错误。 我将前端 URL 添加到 Azure 门户内允许的 CORS 来源,但仍然没有成功。

我还尝试在 NestJs Bootstrap Phase 上启用 CORS

app.enableCors()

但它没有改变。

飞行前 header 不包含任何允许的原始 header 。 我不知道此时我缺少什么。

最佳答案

  • CORS 要求浏览器在发出实际请求之前向服务器发送预检请求 (OPTIONS)。如果预检请求遇到错误,浏览器将停止 future 的请求并发出 CORS 错误。

  • 我希望您已安装 @nestjs/common 软件包并导入 CorsMiddleware

这是我的 main.ts. 文件:

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { CorsOptions } from '@nestjs/common';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  const corsOptions: CorsOptions = {
    origin: 'https://sampleproject.com',
    methods: 'GET,HEAD,PUT,PATCH,POST,DELETE',
    preflightContinue: false,
    optionsSuccessStatus: 204,
    credentials: true,
  };
  app.use('/api', CorsMiddleware(corsOptions));
  await app.listen(3000);
}
bootstrap();

作为临时调试措施,您可以尝试在 NestJS 应用程序的中间件或拦截器中显式设置 CORS header 。

  • 向后端 API 响应添加 header :
import { Injectable, NestMiddleware } from '@nestjs/common';
import { Module, NestModule, MiddlewareConsumer } from '@nestjs/common';
import { CorsMiddleware } from './cors.middleware';

@Module({})
export class AppModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    consumer.apply(CorsMiddleware).forRoutes('*');
  }
}

@Injectable()
export class CorsMiddleware implements NestMiddleware {
  use(req: any, res: any, next: () => void) {
    res.header('Access-Control-Allow-Origin', 'YOUR_FRONTEND_URL');
    res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
    res.header('Access-Control-Allow-Headers', 'Content-Type, Accept');
    next();
  }
}

允许来源、方法和 header ,以确保它们符合您的前端要求。

关于azure - CORS:Azure WebApp Docker 容器内的 NestJs,CORS 被拒绝,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76347577/

相关文章:

javascript - xmlHttpRequest 出现 Phonegap 错误

azure - AppInsights - 监控挂起的进程

azure - 使用 Graph API 在 ADB2C 中创建联合 AD 用户

javascript - 如何通过javascript从html页面中的特定github txt文件中获取数据

amazon-web-services - AWS CloudFront : Font from origin has been blocked from loading by Cross-Origin Resource Sharing policy

azure - 如何从azure应用程序服务连接字符串检索未加密的密码

azure - 如何向 Azure 服务应用程序上运行的 docker 添加其他选项

azure - 在 Azure 应用服务中导出证书

azure - 通过子网连接 CosmosDB 并定义相应的连接字符串

azure - 如何从 Azure Active Directory 获取 postman 中的用户角色声明?