我目前正在尝试在 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/