使用Axios提交表单数据到数据库遇500错误,数据为空
Axios提交表单数据500错误及数据接收问题解决
你判断的方向是对的,问题大概率出在请求体的序列化格式上。以下是具体修改方案:
方案一:显式序列化JSON字符串并指定请求头
如果后端期望接收JSON格式的请求体,手动将数据转为JSON字符串并显式设置Content-Type头,确保后端能正确解析:
const handleSubmit = async () => { try { // 将表单数据转为JSON字符串 const postData = JSON.stringify({ batchId, name, description, source, }); const response = await axios.post( ApiUrl, postData, { headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json', }, } ); console.log(response.data); handleModal(); } catch (error) { // 兼容无response的异常情况 console.error(error.response?.data || error.message); } };
方案二:表单格式提交(若后端期望)
如果后端要求接收application/x-www-form-urlencoded格式的表单数据,改用URLSearchParams处理:
const handleSubmit = async () => { try { const postData = new URLSearchParams({ batchId, name, description, source, }); const response = await axios.post( ApiUrl, postData, { headers: { Authorization: `Bearer ${token}`, // Axios会自动设置Content-Type为application/x-www-form-urlencoded,可省略 }, } ); console.log(response.data); handleModal(); } catch (error) { console.error(error.response?.data || error.message); } };
额外排查点
- 提交前先打印表单变量:
console.log(batchId, name, description, source),确认useState存储的值不为空 - 查看后端服务器日志,500错误通常是后端解析请求或业务逻辑出错,日志能给出更具体的原因
内容的提问来源于stack exchange,提问作者Edgar
相关产品推荐
相关产品推荐

