Javascript NestJS 在生产中启用 cors

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/50949231/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 04:43:01  来源:igfitidea点击:

NestJS enable cors in production

javascriptnode.jstypescriptcorsnestjs

提问by Francesco Borzi

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

我已经按照官方教程在我的 NestJS 应用程序中启用了 CORS ,所以我的main.ts外观如下所示:

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();

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

当我使用npm run start:dev.

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

但是,当我尝试首先使用 编译应用程序npm run webpack然后使用 运行它时node server.js,cors 将不起作用。

The http request from the client will fail with:

来自客户端的 http 请求将失败:

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.

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

采纳答案by Francesco Borzi

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

不知何故,问题是使用npm run webpack. 如果我使用编译它,prestart:prod那么它将起作用。

Thanks @georgii-rychko for suggesting it via comments.

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

回答by Georgii Rychko

Try to use an approach described in here https://docs.nestjs.com/techniques/security#cors

尝试使用此处描述的方法https://docs.nestjs.com/techniques/security#cors

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

回答by David Dehghan

If you are running NestJs with graphql you will run into a problem where Apollo server will override the CORS setting see link. This below fixed the problem. I wasted 8 hrs of my life on this. :-( I hope you see this and you don't do that. see linkand link

如果您使用 graphql 运行 NestJs,您将遇到一个问题,即 Apollo 服务器将覆盖 CORS 设置,请参阅链接。下面解决了这个问题。我为此浪费了 8 个小时的生命。:-( 我希望你看到这个,你不要那样做。见链接链接

        GraphQLModule.forRoot({
            debug: process.env.NODE_ENV !== 'production',
            playground: process.env.NODE_ENV !== 'production',
            typePaths: ['./**/*.graphql'],
            installSubscriptionHandlers: true,
            context: ({req}) => {
                return {req};
            },
            cors: {
                credentials: true,
                origin: true,
            },
        }),

then in your main.ts:

然后在你的 main.ts 中:

        app.enableCors({
            origin: true,
            methods: 'GET,HEAD,PUT,PATCH,POST,DELETE,OPTIONS',
            credentials: true,
        });

回答by antzshrek

Sad to know that you also tried:

很遗憾知道您也尝试过:

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

And it's still not working.

它仍然无法正常工作。



Ensure that on your server side you have corsenabled, which should be something like this:

确保在您的服务器端启用了cors,它应该是这样的:

app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
  res.header('Access-Control-Allow-Headers', 'Content-Type, Accept');
  next();
});

And also ensure that your browser is corssupported. If all these still doesn't work, I will advice you download Allow-Control-Allow-Originextension for Chrome, it should fix your issue.

并确保您的浏览器支持cors。如果所有这些仍然不起作用,我会建议您下载适用于 Chrome 的Allow-Control-Allow-Origin扩展程序,它应该可以解决您的问题。