Home > Blockchain >  Access-Control-Allow-Origin CORS Header missing when uploading large files
Access-Control-Allow-Origin CORS Header missing when uploading large files

Time:01-08

So, when I try to upload a file to NestJS via Angular and FormData, it works fine with pictures and files that is less than ~1-2 MB, but when I try to upload a 9 MB file, the console gives the following error:

Cross-Origin request blocked: The same-origin policy does not allow reading the remote resource from: MyApiLink. (Cause: "Access-Control-Allow-Origin" CORS header is missing). Status code: 413.

Can you tell me why?

Heres my code:

Main.ts (NestJS):

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

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.enableCors()
  await app.listen(3000);
}
bootstrap();

File upload (NestJS):

  @Post("uploadImg")
  @UseInterceptors(
    AnyFilesInterceptor({
      storage: diskStorage({
        destination: function (req: any, file, cb) {
          console.log(file);


          function mkdirRecursiveSync(path: string) {
            if (!existsSync(path)) {
              mkdirRecursiveSync(dirname(path));
              mkdirSync(path);
            }
          }

          const destPath = `CDN/attachments/${req.body.dest}`;
          mkdirRecursiveSync(destPath);
          console.log(req.body)
          cb(null, destPath);
        },
        filename: function (req, file, cb) {
          console.log(file)
          cb(null, file.originalname);
        },
      }),
    })
  )
  async uploadedFile(@UploadedFiles() file) {
    console.log(file)
    return file;
  }

File upload (Angular (Removed some code from it)):

          let formData = new FormData()

          let dateX = cur_day   hours   minutes   seconds;

          formData.append("dest", `${this.chatid}/${this.userData.userid}/${dateX}/`)
          this.draftImages.forEach((fileData: any) => {


            formData.append("file", fileData.file, fileData.name)
            console.log(fileData.file);
          })

          console.log(formData)
          this.http.post<any>("http://localhost:3000/chat/message/dm/uploadImg", formData).subscribe((result) => {
            console.log(result, formData)
            let filesUploaded: any = []
            this.draftImages = []

            Array.from(result).forEach((file: any) => {
              filesUploaded.push(file.destination   file.originalname)
            })

            this.dmService.sendMessage({
              message: message,
              chatid: this.chatid,
              userid: this.userData.userid,
              username: this.userData.username,
              pfp: this.userData.pfp,
              files: filesUploaded
            });

          })
}

CodePudding user response:

You're receiving an HTTP 413 error (Payload Too Large) because of Nginx default configuration.

To accept larger files you need to add client_max_body_size in your configuration file and assign it a value :

client_max_body_size 4m;

As defined in Nginx documentation :

[client_max_body_size] sets the maximum allowed size of the client request body. If the size in a request exceeds the configured value, the 413 (Request Entity Too Large) error is returned to the client. Please be aware that browsers cannot correctly display this error. Setting size to 0 disables checking of client request body size.

If you're curious about why browsers have trouble displaying this kind of error, I recommend you to read this post.

  • Related