大文件上传时出现Access-Control-Allow-Origin CORS Header缺失问题求助
大文件上传报错:CORS头缺失(状态码413)
问题现象
使用Angular结合FormData向NestJS上传文件时,1-2MB以内的文件能正常上传,但上传9MB文件时控制台报错:
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.
原因分析
报错里的状态码413是核心线索,它表示「请求实体过大(Payload Too Large)」。之所以同时提示CORS头缺失,是因为当NestJS底层的Express服务器拒绝大请求时,会直接返回413响应,此时还没走到NestJS的CORS中间件逻辑,导致响应里没有带上CORS相关头,浏览器就误报成CORS问题。
本质问题是服务器默认的请求大小限制被触发,而非真正的CORS配置错误。
解决方案
需要从两个层面调整配置:
1. 调整NestJS/Express的请求体大小限制
在main.ts中,添加bodyParser的大小限制配置,同时保留CORS启用:
import { NestFactory } from '@nestjs/core'; import { AppModule } from './app.module'; import { json, urlencoded } from 'express'; async function bootstrap() { const app = await NestFactory.create(AppModule); // 调整请求体大小限制为10MB(可根据需求修改) app.use(json({ limit: '10mb' })); app.use(urlencoded({ extended: true, limit: '10mb' })); app.enableCors(); await app.listen(3000); } bootstrap();
2. 调整文件上传拦截器的大小限制
在AnyFilesInterceptor中显式设置文件大小限制,避免拦截器层面提前拒绝请求:
@Post("uploadImg") @UseInterceptors( AnyFilesInterceptor({ storage: diskStorage({ destination: function (req: any, file, cb) { function mkdirRecursiveSync(path: string) { if (!existsSync(path)) { mkdirRecursiveSync(dirname(path)); mkdirSync(path); } } const destPath = `CDN/attachments/${req.body.dest}`; mkdirRecursiveSync(destPath); cb(null, destPath); }, filename: function (req, file, cb) { cb(null, file.originalname); }, }), // 设置单文件大小限制为10MB limits: { fileSize: 10 * 1024 * 1024 }, }) ) async uploadedFile(@UploadedFiles() file) { console.log(file) return file; }
补充说明
- 若使用Fastify作为NestJS底层服务器,需调整
bodyLimit参数来设置请求大小限制。 - 可根据业务需求,逐步增大限制值以覆盖实际文件上传场景。
内容的提问来源于stack exchange,提问作者Almaszosz
相关产品推荐
相关产品推荐

