在 NestJs 中启用 Cors

Posted

技术标签:

【中文标题】在 NestJs 中启用 Cors【英文标题】:Enable Cors in NestJs 【发布时间】:2020-02-18 11:20:37 【问题描述】:

我想使用 NestJs 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.

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

fetch('http://localhost:3000/articles')
    .then((res) => 
      console.log(res);
    );

我在我的 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();

尝试 B

async function bootstrap() 
  const app = await NestFactory.create(AppModule);
  app.enableCors();
  await app.listen(3000);

bootstrap();

尝试 C

async function bootstrap() 
  const app = await NestFactory.create(AppModule, cors: true);
  await app.listen(3000);

bootstrap();

【问题讨论】:

nestjs 使用 expressjs/cors github.com/expressjs/cors 中的 cors 模块。 origin: true 属性用于每个路由以启用该特定路由的 cors。由于这是一个普遍的变化,我想我会尝试将其更改为 origin: '*' 以查看它是否有效。最终它应该是发起请求的域 @VladNeacsu 同样是 '*''localhost''localhost:4200' 一定有一个不相关的问题,因为您的代码中的第二个示例 app.enableCors(); 似乎工作正常。您是否尝试在更改后重新启动应用程序?此外,端口无关紧要,并且由于错误您没有发出跨域请求 响应的 HTTP 状态码是什么?您可以使用浏览器开发工具中的网络窗格进行检查。是 4xx 还是 5xx 错误而不是 200 OK 成功响应? 这能回答你的问题吗? NestJS enable cors in production 【参考方案1】:

在你的main.ts上,编辑引导功能如下启用CORS

const app = await NestFactory.create(AppModule,  cors: true );

或者

const app = await NestFactory.create(ApplicationModule);
app.enableCors();

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

阅读更多关于CORS here

【讨论】:

【参考方案2】:

您可以使用cors npm 模块。通过运行命令安装 corsnpm install cors --save

安装后,在您的 main.ts 文件中粘贴以下行。

app.use(cors());

【讨论】:

【参考方案3】:

CORS 标头的替代方法是在您的计算机上建立一个网络服务器,例如 Nginix,并通过它代理您的所有请求,并根据 url 根转发到适当的端口。这就是现实世界中通常的处理方式,因为 CORS 标头相对较新,默认情况下可能会打开您可能不想要的安全漏洞。

这解决了根本问题,即您的应用程序运行在与您要访问的 api 不同的 Origin(协议 + 域 + 端口)上。

【讨论】:

【参考方案4】:

main.ts

const app = await NestFactory.create(AppModule);
app.enableCors(
    origin: '*',
    methods: 'GET, PUT, POST, DELETE',
    allowedHeaders: 'Content-Type, Authorization',
);
await app.listen(3000);

【讨论】:

以上是关于在 NestJs 中启用 Cors的主要内容,如果未能解决你的问题,请参考以下文章

在 Node 框架 NestJS-6.3.1 中面对 CORS

NestJS使cors能够投入生产

Nest.js 中使用 @nestjs/passport 的可选身份验证

Axios.all 在 Nestjs 中可用吗?

在 Nestjs 中注入 Tree Typeorm 存储库

在 NestJS 中添加标头 HttpRequest