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

浏览器中Axios上传非JPEG文件请求持续pending,Postman正常

问题分析与解决方案

核心问题

  1. 前端Promise未处理错误:你的createProduct函数返回的Promise仅在请求成功时resolve,未捕获axios请求的异常,也未调用reject,导致请求失败时Promise一直处于pending状态,前端无法感知错误。
  2. 错误设置请求头:手动给axios请求设置"Content-Type": "multipart/form-data"会覆盖FormData自动生成的带boundary的请求头,后端解析multipart数据时会出现异常(Postman会自动处理boundary,因此测试正常)。
  3. 后端错误响应状态码不规范:当前错误返回使用200状态码,不符合REST规范,可能导致前端对错误的识别和处理异常。

修复步骤

1. 前端代码修复

修改createProduct函数,移除手动设置的Content-Type,并添加错误捕获逻辑:

export function createProduct(data) {
    return new Promise(async (resolve, reject) => { // 添加reject参数
        const newProduct = new FormData();
        newProduct.append('name', data.name)
        newProduct.append('short_desc', data.short_desc)
        newProduct.append('description', data.description)
        newProduct.append('sizes', JSON.stringify(data.sizes))
        newProduct.append('category', data.category)
        for (let i = 0; i < data.images.length; i++) {
            newProduct.append('images', data.images[i]);
        }

        let config = {
            method: 'post',
            withCredentials: true,
            maxBodyLength: Infinity,
            maxContentLength: Infinity,
            url: 'http://localhost:8080/api/products',
            // 移除手动设置的Content-Type,axios会自动生成带boundary的正确请求头
            data: newProduct
        };

        try {
            const response = await axios.request(config);
            console.log(response)
            resolve({ data: { created: true } });
        } catch (err) {
            // 捕获错误并触发reject,让前端能处理失败场景
            console.error(err);
            reject(err.response?.data || { error: 'Request failed' });
        }
    })
}

2. 后端代码优化

调整错误响应的状态码,让前端能正确识别错误类型:

// handleUploads.js
const handleUploads = (req, res, next) => {
    upload(req, res, (err) => {
        if (err) {
            console.log(err)
            // 返回400状态码,表示客户端请求参数不符合要求
            return res.status(400).json({ error: 'Validation error', message: err.message });
        }
        next();
    });
}

同时可以优化fileFilter的格式校验逻辑,兼容更多JPEG相关格式:

fileFilter: function (req, file, cb) {
    // 兼容jpeg和jpg两种MIME类型
    const allowedTypes = ['image/jpeg', 'image/jpg'];
    if (allowedTypes.includes(file.mimetype)) {
        cb(null, true)
    } else {
        cb(new Error("Only JPEG/JPG images are supported"), false);
    }
}

验证逻辑

  • 上传非JPEG文件时,后端会立即返回400错误响应,前端通过catch捕获并处理,不会出现请求pending的情况。
  • 移除手动设置的Content-Type后,axios会自动生成正确的multipart请求头,后端能正常解析表单数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 21:26:24