NestJS在生产中启用cors [英] NestJS enable cors in production

查看:633
本文介绍了NestJS在生产中启用cors的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

官方教程之后,我已经在NestJS应用中启用了CORS,所以我的如下所示:

I've enabled CORS in my NestJS app following the official tutorial, so my main.ts looks like the following:

import { FastifyAdapter, NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';

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

,当我使用npm run start:dev运行应用程序时,它就可以工作.

and it works when I run the application using npm run start:dev.

但是,当我尝试先使用npm run webpack编译应用程序,然后使用node server.js运行该应用程序时,CORS将无法正常工作.

However when I try to first compile the application using npm run webpack and then running it using node server.js, the cors will not work.

来自客户端的http请求将失败,并显示以下信息:

The http request from the client will fail with:

对预检请求的响应未通过访问控制检查:所请求的资源上不存在"Access-Control-Allow-Origin"标头.因此,不允许访问来源' http://localhost:8000 .响应的HTTP状态代码为404.

Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8000' is therefore not allowed access. The response had HTTP status code 404.

推荐答案

某种程度上,问题是使用npm run webpack进行编译的.如果我使用prestart:prod进行编译,它将可以正常工作.

Somehow the issue was compiling it using npm run webpack. If I compile it using prestart:prod then it will work.

感谢@ georgii-rychko通过评论提出建议.

Thanks @georgii-rychko for suggesting it via comments.

这篇关于NestJS在生产中启用cors的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆