在之前做的项目中,基本上都是使用webpack中的devServer.proxy做本地接口代理,来避免联调时,出现的跨域问题。新公司中使用的却是Nginx做接口代理,在一般的联调中,如果是json数据的通信是没有什么问题的,但是在上传文件时,对于Nginx的配置就有点讲究了。
在做一个上传文件的需求时,上传几十kb的文件都报500 Internal Server Error错误,错误信息:
但是,使用postman上传时却是正常的,最初以为是后端对于访问接口的域名有白名单限制导致,经过一番排查,发现也不是。
后面阴差阳错的上传一个很小的文件(几十kb),发现可以上传成功,因此,让后端定位下是否对上传的文件有大小限制?
其实使用postman上传时,十几M的文件也是可以上传的,因此,也排除了后端的文件大小限制
经过大半天的排查,终于将问题锁定在了上图中错误信息下的: nginx/1.21.3,经过一番排查,主要是由于nginx的配置导致的文件上传错误,与两个配置有关:
client_body_buffer_size
Nginx官方配置说明:
Sets buffer size for reading client request body. In case the request body is larger than the buffer, the whole body or only its part is written to a temporary file. By default, buffer size is equal to two memory pages. This is 8K on x86, other 32-bit platforms, and x86-64. It is usually 16K on other 64-bit platforms.
简单的说就是设置用于读取客户端请求正文的缓冲区大小,如果请求body尺寸超过该设置的buffer,那么整个body或部分将被写入临时文件中。
client_max_body_size
Nginx官方配置说明:
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
sizeto 0 disables checking of client request body size.
该配置主要用于设置客户端请求body的尺寸大小,如果超过该尺寸,则会相应413的错误
解决 500 Internal Server Error
经过测试如果上传的文件大小超过client_body_buffer_size配置的大小,则会报500错误,按照官方的配置说明,如果超过,应该是保存在临时文件中,为什么会报500错误?这个问题还未得出答案,暂时将其设置为100m来避免该错误
解决 413 Request Entity Too Large
如果上传的文件大小超过client_max_body_size配置大小,则会报413错误。
官方配置说设置size为0可以关闭该检查,但是实际测试发现设置为0时,并未关闭该检查,因此,设置为1024来避免错误