在 NestJs 中启用 Cors

s g*_*ace 6 cors nestjs

我想使用 NestJs api,但在每个 api 中都收到相同的错误消息fetch

Access to fetch at 'http://localhost:3000/articles' from origin 'http://localhost:4200' has been blocked by CORS policy: 
No 'Access-Control-Allow-Origin' header is present on the requested resource.
If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
Run Code Online (Sandbox Code Playgroud)

我的前端是一个 Angular,我有一个简单的fetch

fetch('http://localhost:3000/articles')
    .then((res) => {
      console.log(res);
    });
Run Code Online (Sandbox Code Playgroud)

我在 NestJs 中尝试了这些选项 - 但它们似乎都不起作用:

尝试 A

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.enableCors({
    origin: true,
    methods: 'GET,HEAD,PUT,PATCH,POST,DELETE',
    allowedHeaders: 'Content-Type, Accept',
  });
  await app.listen(3000);
}
bootstrap();
Run Code Online (Sandbox Code Playgroud)

尝试 B

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.enableCors();
  await app.listen(3000);
}
bootstrap();
Run Code Online (Sandbox Code Playgroud)

尝试 C

async function bootstrap() {
  const app = await NestFactory.create(AppModule, {cors: true});
  await app.listen(3000);
}
bootstrap();
Run Code Online (Sandbox Code Playgroud)

Raj*_*nan 5

在您的 上main.ts,按如下方式编辑引导程序功能以启用CORS

const app = await NestFactory.create(AppModule, { cors: true });
Run Code Online (Sandbox Code Playgroud)

或者

const app = await NestFactory.create(ApplicationModule);
app.enableCors();
Run Code Online (Sandbox Code Playgroud)

此方法可帮助您为 cors 传递额外的参数

在此处阅读有关CORS 的更多信息