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

Cannot read properties of undefined (reading 'transfer-encoding')错误求助

解决 "Cannot read properties of undefined (reading 'transfer-encoding')" 错误

核心问题:multer中间件参数顺序颠倒

你在调用multer的upload函数时,把res和req的参数顺序写反了。multer的处理函数要求第一个参数是请求对象req,第二个是响应对象res,顺序错误会导致multer内部无法正确读取请求头,从而抛出transfer-encoding相关的未定义错误。

修正后的路由代码片段:

express.post('/', (req, res) => {
    // 修正参数顺序:req在前,res在后
    upload(req, res, async (error) => {
        // validate request
        if (!req.file) {
            return res.json({ error: "Files are not valid :(" })
        }
        if (error) {
            return res.status(500).send({ error: error.message })
        }

        // store into database 
        const file = new File({
            filename: req.file.filename,
            uuid: uuid4(),
            path: req.file.path,
            size: req.file.size
        })

        const response = await file.save();
        return res.json({ file: `${process.env.APP_BASE_URL}/files/${response.uuid}` })
    })
})

其他潜在问题修正

  • 目录拼写错误:存储路径'uplods/'应为'uploads/',避免文件存储时找不到目录
  • multer配置项错误:limit需改为复数limits,否则文件大小限制不生效
  • 确保目录存在:multer不会自动创建uploads目录,需手动创建该目录,或在代码中添加目录检查逻辑

修正后的完整代码:

require('dotenv').config()
const express = require('express').Router();
const multer = require('multer');
const path = require('path');
const fs = require('fs');
const File = require('../models/file');
const { v4: uuid4 } = require('uuid');

// 确保uploads目录存在
const uploadDir = 'uploads/';
if (!fs.existsSync(uploadDir)) {
    fs.mkdirSync(uploadDir);
}

let storage = multer.diskStorage({
    destination: (req, file, cb) => cb(null, uploadDir),
    filename: (req, file, cb) => {
        const uniqueName = `${Date.now()}-${Math.round(Math.random() * 1E9)}${path.extname(file.originalname)}`;
        cb(null, uniqueName)
    },
})

let upload = multer({
    storage,
    limits: { fileSize: 1000000 * 100 }, // 修正为limits
}).single('myfile');

express.post('/', (req, res) => {
    upload(req, res, async (error) => {
        if (!req.file) {
            return res.json({ error: "Files are not valid :(" })
        }
        if (error) {
            return res.status(500).send({ error: error.message })
        }

        const file = new File({
            filename: req.file.filename,
            uuid: uuid4(),
            path: req.file.path,
            size: req.file.size
        })

        const response = await file.save();
        return res.json({ file: `${process.env.APP_BASE_URL}/files/${response.uuid}` })
    })
})

module.exports = express;

错误截图:
Cannot read properties of undefined (reading 'transfer-encoding')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 12:05:22