Node.js提交表单时报TypeError: Cannot read property 'file' of null如何解决
报错原因
当用户未上传文件时,files变量的值为null,代码未做非空校验直接访问files.file,就会触发Cannot read property 'file' of null的类型错误。
修复方案
在调用文件上传逻辑前增加非空判断即可,可根据你的运行环境选择对应写法:
- 支持ES2020+的环境(可选链写法):
if (files?.file) { writeFileToCloudinary(files.file) .then((secureUrl) => { Posts.update( { image1_url: secureUrl }, { where: { id: postId } } ); }) // 建议添加上传异常捕获,避免未处理的Promise报错 .catch((err) => { console.error('文件上传失败:', err); }); } // 若需在无文件时给字段设置默认值,可补充else分支 else { Posts.update( { image1_url: '' }, { where: { id: postId } } ); }
- 低版本兼容写法:
if (files && files.file) { writeFileToCloudinary(files.file) .then((secureUrl) => { Posts.update( { image1_url: secureUrl }, { where: { id: postId } } ); }) .catch((err) => { console.error('文件上传失败:', err); }); } else { Posts.update( { image1_url: '' }, { where: { id: postId } } ); }
内容的提问来源于stack exchange,提问作者Divad
相关产品推荐
相关产品推荐

