When uploading a file, the request doesn't even get to the controller and gets rejected with Access to XMLHttpRequest at 'http://domainname.com/api/app/upload' from origin 'http://domainname.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
async function bootstrap() {
const app = await NestFactory.create<NestExpressApplication>(
ApplicationModule,
new ExpressAdapter(),
);
app.enableCors({ origin: true });
await app.listen(parseInt(settings.port.toString()), '0.0.0.0');
}
bootstrap();
@Post('upload')
@UseInterceptors(FileInterceptor('file'))
upload(@Body() body, @UploadedFile() file) {
if (!file) throw new HttpException('request.incomplete', HttpStatus.BAD_REQUEST);
return this.appService.upload(file, body.folder);
}
I've tried every solution found here https://github.com/nestjs/nest/issues/1134 for the app.enableCors(options) options parameter. None of them worked.
Nest version: 6.11.4
Please, use our Discord channel (support) for such questions. We are using GitHub to track bugs, feature requests, and potential improvements. CORS-related problems have been tracked many times in the past and they were all the result of incorrect app settings.
@kamilmysliwiec thank you for your work with Nestjs but maybe you should think again when addressing issues, specially CORS. As everyone else, I've followed the docs https://docs.nestjs.com/techniques/security#cors its pretty straightforward and not many lines of code. So not many errors possible here. And still not working properly.
You're right, maybe it's not a bug but definitely a lack of documentation...
@FlawaCLV did you managed to get it to work? it seems we've stumbled across the same issue.
@sclausen nope, never made it work. I went for stream upload instead of http out of desperation.
Just for anybody encountering the same problem: We had a kubernetes cluster and the nginx ingress controller was configured without a body limit. We found the solution for our problem here.
Similar to @sclausen, I was getting this error due to nginx's default client_max_body_size value. My form was allowing up to 20MB, but nginx's default limit is 1MB. Adding client_max_body_size 20M; in my server block and reloading my nginx config fixed the issue.
Most helpful comment
Just for anybody encountering the same problem: We had a kubernetes cluster and the nginx ingress controller was configured without a body limit. We found the solution for our problem here.