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

使用Node.js/Express.js API上传图片时出现404错误求助

Node.js/Express图片上传接口404问题排查与修复

核心问题分析

1. 路由路径不匹配

你的代码中定义的POST接口路径是/upload,但Postman请求的是localhost:3000/api/upload,路径前缀/api未在接口定义中体现,这是导致404错误的直接原因。

2. 控制台日志拼写错误

代码中consloe.log('i am hereeeeeee')存在拼写错误(少了一个字母l),正确写法是console.log,这就是控制台无日志输出的原因。

修复步骤

步骤1:修正路由路径

将接口路径改为/api/upload,与Postman的请求路径匹配:

app.post('/api/upload', upload.single('image'), async (req, res) => {
    // ... 原有代码
});

如果你的项目使用了路由拆分,可以通过app.use('/api', router)给整个路由组添加/api前缀,无需逐个修改接口。

步骤2:修复日志拼写错误

把consloe.log改为console.log,确保请求到达时能在控制台看到日志输出。

步骤3:额外检查项

  • 手动创建uploads/文件夹:multer不会自动生成目标目录,若该文件夹不存在,上传时会抛出错误。
  • 确认Postman请求格式:选择form-data类型,将key设为image,类型选择File后再上传文件,不要使用raw或其他格式。
  • 验证服务端口:确保Express服务确实运行在3000端口,无端口冲突。

修正后的完整代码片段

const upload = multer({ dest: 'uploads/' });
const saveImageToDatabase = async (filename) => {
  console.log('file uploaded');
  try {
    // Simulating saving image to the database
    await new Promise((resolve) => setTimeout(resolve, 2000));
    console.log(`Saved ${filename} to the database`);
  } catch (error) {
    console.error('Error saving image to the database:', error);
    throw error;
  }
};

app.post('/api/upload', upload.single('image'), async (req, res) => {
    console.log('i am hereeeeeee');
  try {
    const file = req.file;

    if (!file) {
        console.log('no file uploaded');
      res.status(400).json({ error: 'No file uploaded' });
      return;
    }

    await saveImageToDatabase(file.filename);

    res.status(200).json({ message: 'File uploaded and saved successfully' });
  } catch (error) {
    res.status(500).json({ error: 'An error occurred while uploading the file' });
  }
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 05:25:23