NestJS enable cors in production(NestJS 在生产中启用 cors)
问题描述
我已经按照 官方教程在我的 NestJS 应用中启用了 CORS,所以我的 main.ts
如下所示:
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"标头.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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:NestJS 在生产中启用 cors


- Fetch API 如何获取响应体? 2022-01-01
- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- Flexslider 箭头未正确显示 2022-01-01
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- 失败的 Canvas 360 jquery 插件 2022-01-01
- addEventListener 在 IE 11 中不起作用 2022-01-01
- 400或500级别的HTTP响应 2022-01-01