React表单提交至Express后端,req.body返回空对象的解决方法
问题解决:React表单POST数据到Express,req.body为空的处理方案
你的问题出在两个地方,分别在后端Express和前端React代码里,改完就能正常获取请求体了:
1. Express后端:添加JSON请求体解析中间件
你当前只配置了express.urlencoded来解析表单格式的数据,但前端发的是JSON格式的请求体,所以需要添加JSON解析中间件。另外现在Express已经内置了body-parser的功能,不需要单独引入body-parser包,可以直接删掉。
修改后的Express代码:
const express=require('express') const app=express() const cors=require('cors') const port=process.env.port|| 5000 // 修正:process.port应为process.env.port app.use(cors()) // 新增JSON解析中间件,处理前端传来的JSON格式请求体 app.use(express.json()); // 保留urlencoded解析(若需处理表单默认格式的场景) app.use(express.urlencoded({ extended: true })); const students=[ {name:'salim',age:15}, {name:'rafik',age:16}, {name:'atik',age:17}, ] app.get('/',(req,res)=>{ res.send(students) }) app.post('/post',(req,res)=>{ console.log(req.body); console.log('post hited'); // 给前端返回响应,避免fetch请求挂起 res.json({message: '数据接收成功', data: req.body}) }) app.listen(port,()=>{ console.log(`Listening Port is ${port}`); })
2. React前端:修正fetch的headers拼写错误
你代码里把headers写成了header(单数),导致Content-type: application/json这个头没正确设置,后端无法识别请求体格式,自然解析不到数据。
修改后的React代码:
import { useEffect, useState } from 'react'; import './App.css'; function App() { const [user,setUser]=useState() useEffect(()=>{ fetch('http://localhost:5000/') .then(res=>res.json()) .then(data=>console.log(data)) },[]) const handleSubmit=(e)=>{ e.preventDefault() const form=e.target const name=form.name.value const age=form.age.value const newUser={name,age} console.log(newUser); fetch('http://localhost:5000/post',{ method:'POST', // 修正:header改为headers(复数) headers:{ 'Content-type':'application/json', }, body:JSON.stringify(newUser) }) .then(res=>res.json()) .then(data=>{ console.log(data); form.reset() // 恢复表单重置逻辑 }) .catch(err=>console.error('请求出错:', err)) // 新增错误捕获,方便排查问题 } return ( <div className="App"> <form action="" onSubmit={handleSubmit}> <input type="text" name='name' placeholder="输入姓名" /> <input type="text" name='age' placeholder="输入年龄" /> <button type='submit'>Submit</button> </form> </div> ); } export default App;
额外补充两个小细节:
- Express里的
process.port是错误写法,正确应为process.env.port,确保环境变量中的PORT设置能生效; - 后端POST接口必须返回响应,否则前端fetch会一直处于pending状态;前端建议添加错误捕获,方便排查请求失败的场景。
内容的提问来源于stack exchange,提问作者iftekhar
相关产品推荐
相关产品推荐

