已配置中间件,Express为何仍读取到Axios POST的空请求体?
React POST请求到Express API时req.body为空的问题修复
尝试从React应用向Express API发送POST请求,Postman用
x-www-form-urlencoded格式能正常提交,但React发送时API端的req.body为空/undefined。React端能看到请求体和请求头数据,但API端打印为空。
修复步骤
1. 修正Content-Type拼写错误
你的Axios请求头里Content-Type拼写错误:appliation/x-www-form-urlencoded 应改为 application/x-www-form-urlencoded(缺失字母c)。
2. 将请求体转为URLSearchParams格式
Axios默认会把JS对象序列化为JSON,即便设置了x-www-form-urlencoded的Content-Type也无效。必须手动将对象转为URLSearchParams格式,同时注意键名要和API端req.body的键名完全一致(API里用的是大写开头的Name,不是小写name):
let submitLonghorn = async (e: any) => { e.preventDefault(); const longhorn = new URLSearchParams(); longhorn.append('Name', name); longhorn.append('RanchPrefix', ranchPrefix); longhorn.append('RoleID', roleID); longhorn.append('SexID', sexID); longhorn.append('FatherLonghornID', fatherLonghornID); longhorn.append('MotherLonghornID', motherLonghornID); longhorn.append('ReferenceNumber', referenceNumber); longhorn.append('DOB', dob); longhorn.append('Description', description); const config = { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }; axios.post('http://127.0.0.1:8081/longhorns/add', longhorn, config) .then(() => console.log("Longhorn added")) .catch(err => console.error(err)); };
3. 优化Express中间件配置
建议全局挂载express.urlencoded中间件,确保所有路由都能处理x-www-form-urlencoded格式的请求:
// 替换原有的路由级中间件配置 app.use(express.urlencoded({ extended: true }));
4. 修复SQL注入风险(关键)
当前直接拼接SQL参数的写法存在严重SQL注入风险,改用参数化查询:
app.post('/longhorns/add', async function (req, res) { try { // 确保已正确配置数据库连接 const pool = await sql.connect(process.env.DB_CONFIG); await pool.request() .input('Name', sql.NVarChar, req.body.Name) .input('RanchPrefix', sql.NVarChar, req.body.RanchPrefix) .input('RoleID', sql.Int, parseInt(req.body.RoleID)) .input('SexID', sql.Int, parseInt(req.body.SexID)) .input('FatherLonghornID', sql.Int, parseInt(req.body.FatherLonghornID)) .input('MotherLonghornID', sql.Int, parseInt(req.body.MotherLonghornID)) .input('ReferenceNumber', sql.NVarChar, req.body.ReferenceNumber) .input('DOB', sql.Date, req.body.DOB) .input('Description', sql.NVarChar, req.body.Description) .execute('AddLonghorn'); res.status(200).send('Longhorn added successfully'); } catch (err) { console.error(err); res.status(500).send('Failed to add longhorn'); } });
内容的提问来源于stack exchange,提问作者8times9
相关产品推荐
相关产品推荐

