You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Mocha Node.js测试中文件上传出现[Object null prototype]问题求助

解决express-fileupload返回[Object null prototype]的问题

问题说明

使用express-fileupload处理文件上传时,req.files返回的对象格式为[Object null prototype] { file: { ... }},无论通过Mocha测试还是外部客户端调用都会出现这个问题。尝试过app.use(bodyParser.urlencoded({extended: true}))和JSON.stringify(req.files)临时处理,但需要彻底解决。

问题根源

express-fileupload库为了防止原型污染,默认使用Object.create(null)创建文件对象,这类对象没有原型链,因此会显示为[Object null prototype]。

彻底解决方案

方案1:路由内手动转换为普通对象

在路由中直接将null原型对象转换为普通对象,使用对象展开运算符或Object.assign:

router.post('/doc', async (req, res) => {
  // 转换单个文件对象
  const uploadedFile = { ...req.files.file };
  // 如果有多个文件,批量转换
  // const convertedFiles = Object.fromEntries(
  //   Object.entries(req.files).map(([key, file]) => [key, { ...file }])
  // );
  console.log(uploadedFile); // 此时为普通对象
});

方案2:全局中间件统一转换

添加全局中间件,自动将所有请求中的req.files转换为普通对象,避免每个路由重复处理:

// 在server.js的express-fileupload中间件之后添加
app.use((req, res, next) => {
  if (req.files) {
    req.files = Object.fromEntries(
      Object.entries(req.files).map(([key, file]) => {
        // 兼容单个文件或文件数组的情况
        const convertedFile = Array.isArray(file) 
          ? file.map(item => ({ ...item })) 
          : { ...file };
        return [key, convertedFile];
      })
    );
  }
  next();
});

修改后的完整server.js示例:

import express from 'express'
import authentication from './src/login.js'
import './global/host.js'
import bodyParser from 'body-parser'
import cors from "cors"
import verifyToken from './middleware/auth.js'
import { userAction1, userAction2 } from './src/userAction.js'
import verifyLevel from './middleware/level.js'
import fileUpload from 'express-fileupload';

export default function myApp() {
    const whitelist = [/http:\/\/localhost:\*/, /http:\/\/127.0.0.1:\*/]
    const corsConfig = { origin: whitelist }
    const app = express();
    const port = hostPort;

    // 解析请求体
    app.use(bodyParser.urlencoded({ extended: true }));
    app.use(bodyParser.json())
    app.use(cors(corsConfig))

    // 启用文件上传
    app.use(fileUpload({
        createParentPath: true
    }));

    // 全局转换req.files为普通对象
    app.use((req, res, next) => {
        if (req.files) {
            req.files = Object.fromEntries(
                Object.entries(req.files).map(([key, file]) => {
                    const convertedFile = Array.isArray(file) 
                        ? file.map(item => ({ ...item })) 
                        : { ...file };
                    return [key, convertedFile];
                })
            );
        }
        next();
    });

    app.use('/usrAction1', userAction1())

    app.listen(port, () => {
        console.log(`Example app listening at http://localhost:${port}`);
    });
    return app;
}
myApp();

验证修改

修改完成后,在路由中打印req.files,输出会变为普通的[Object Object]格式,无需再通过JSON.stringify处理。

内容的提问来源于stack exchange,提问作者hauretax

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 18:20:32