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

如何不携带图片提交表单?提交时触发TypeError错误求助

解决无图片提交时的TypeError问题

问题核心是未上传图片时req.file为undefined,直接访问req.file.filename会触发类型错误。只需添加req.file的存在判断,即可按需处理image字段:

module.exports.createComment = async (req, res) => {
  try {
    if (!req.body.message) {
      return res.status(400).send({
        message: "Content can not be empty!"
      });
    }
    let { id, message, date, image } = req.body;
    // 仅当存在上传文件时拼接图片URL,否则设为null
    if (req.file) {
      image = `${req.protocol}://${req.get("host")}/images/${req.file.filename}`;
    } else {
      image = null; // 若业务允许,也可保留undefined
    }
    const comment = await Comment.create({ id, message, date, image });
    return res.status(201).send(comment);
  } catch (error) {
    console.log(error);
    return res.send(`Error: ${error}`);
  }
};

关键修改说明:

  • 增加if (req.file)条件判断,避免无文件时访问req.file.filename导致报错
  • 无图片时将image设为null(或保留undefined,取决于数据库字段的允许值)
  • 替换.then()为await,与外层async语法统一,简化代码结构

修改后,在Postman中不携带图片提交时,image字段会被正确设为null,不会再触发类型错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 21:27:25