无法向服务器发送FormData对象,请求抛出TypeError错误
问题:无法通过Axios发送FormData对象上传文件
问题描述
通过Axios拦截器封装API后,调用uploadFile接口上传文件时,请求Payload中无文件数据,同时抛出错误:
Cannot read properties of undefined (reading 'data') TypeError: Cannot read properties of undefined (reading 'data') at getImage (http://localhost:3000/static/js/bundle.js:809:33)
相关代码涉及:Axios拦截器封装(api.js)、接口常量配置(config.js)、文件上传逻辑(CreatePost.jsx)。
问题分析
- Content-Type配置错误:axios实例默认固定
"Content-Type": "application/json",但上传FormData时,axios会自动检测并设置multipart/form-data请求头,手动固定的application/json会覆盖自动配置,导致后端无法解析FormData。 - 响应处理逻辑缺陷:
processResponse函数在响应状态非200时返回的对象不含data字段,若前端尝试访问response.data,会触发undefined读取错误。
解决方案
1. 修复axios请求头配置
修改api.js中的axios实例创建逻辑,移除固定的Content-Type,让axios自动根据请求数据类型设置:
const axiosInstance = axios.create({ baseURL: API_URL, timeout: 10000, headers: { Accept: "application/json, multipart/form-data", // 支持接收多种响应类型 // 移除固定的Content-Type,交由axios自动处理 }, });
或者通过请求拦截器动态配置:
axiosInstance.interceptors.request.use( function (config) { // 仅当数据不是FormData时,设置application/json if (!(config.data instanceof FormData)) { config.headers["Content-Type"] = "application/json"; } return config; }, function (error) { return Promise.reject(error); } );
2. 完善响应处理函数
修改api.js中的processResponse,确保所有返回对象都包含data字段:
const processResponse = (response) => { if (response?.status === 200) { return { isSuccess: true, data: response.data }; } else { return { isFailure: true, status: response?.status, msg: response?.data?.msg || API_NOTIFICATION_MESSAGES.responseFailure, code: response?.status, data: response?.data || null // 新增data字段,避免undefined }; } };
3. 确认接口路径正确性
检查config.js中uploadFile的路径,确保和后端接口匹配:
export const SERVICE_URLS = { // ...其他接口 uploadFile: { url: "/file/upload", method: "POST" }, // 确保路径与后端一致 };
4. 优化前端调用的错误处理
在CreatePost.jsx中明确处理响应状态,避免访问undefined属性:
useEffect(() => { const getImage = async () => { if (!file) return; const data = new FormData(); data.append("name", file.name); data.append("file", file); try { const response = await API.uploadFile(data); if (response.isSuccess) { console.log("上传成功", response.data); // 后续业务逻辑 } else { console.log("上传失败", response.msg); } } catch (error) { console.log("请求错误", error.msg); } }; getImage(); }, [file]);
验证步骤
- 重启前端项目,确保代码修改生效。
- 选择文件上传,打开浏览器开发者工具的Network面板,确认:
- 请求的Content-Type为
multipart/form-data; boundary=... - FormData Payload包含
name和file字段
- 请求的Content-Type为
- 检查后端是否正确接收到文件数据。
内容的提问来源于stack exchange,提问作者Astha Negi
相关产品推荐
相关产品推荐

