问题
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();
and it works when I run the application using npm run start:dev
.
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.
The http request from the client will fail with:
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.
回答1:
Try to use an approach described in here https://docs.nestjs.com/techniques/security#cors
const app = await NestFactory.create(ApplicationModule);
app.enableCors();
await app.listen(3000);
回答2:
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 link and link
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:
app.enableCors({
origin: true,
methods: 'GET,HEAD,PUT,PATCH,POST,DELETE,OPTIONS',
credentials: true,
});
回答3:
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 cors enabled, which should be something like this:
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 cors supported. If all these still doesn't work, I will advice you download Allow-Control-Allow-Origin extension for Chrome, it should fix your issue.
回答4:
Somehow the issue was compiling it using npm run webpack
. If I compile it using prestart:prod
then it will work.
Thanks @georgii-rychko for suggesting it via comments.
来源:https://stackoverflow.com/questions/50949231/nestjs-enable-cors-in-production