React与Node.js交互:POST请求空体及GET请求查询异常问题
I’ve worked through two typical headaches that pop up when connecting a React frontend to an Express backend—let’s break down each problem and their straightforward fixes:
1. Empty req.body on POST Requests
The Problem
When submitting a POST request from React using fetch with JSON data, the Express server logs an empty req.body instead of the expected post payload.
Frontend React Code:
fetch("http://localhost:3001/create", { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(post) }) .then(res => this.props.history.push('/posts')) .catch(err => this.setState({error: true})) this.setState({ title: "", body: "" })
Original Express Server Code:
app.post('/create', (req, res, next)=>{ // Request body is empty, why? console.log(req.body); })
The Fix
Your frontend is sending JSON-formatted data, but your Express server isn’t set up to parse JSON payloads. The body-parser.urlencoded middleware only handles form data, not JSON. Add the JSON parsing middleware to your server setup:
// Add this line alongside your existing body-parser configuration app.use(bodyParser.json());
Once you add this, Express will correctly parse the JSON body from the POST request, and req.body will contain your post data as expected.
2. TypeError: Cannot read property 'id' of undefined on GET Requests with URL Params
The Problem
When fetching a post by ID via a URL parameter, the server throws a TypeError because the findPostById function fails to locate the matching post, leaving post as undefined when trying to access post.id.
Frontend React Code:
fetch(`http://localhost:3001/posts/${this.props.match.params.id}`) .then(res=>res.json()) .then(data=>this.setState({loadedPost: data})) .catch(err=>console.log(err))
Original Express Server Code:
app.get('/posts/:id', (req, res, next)=>{ // Correctly receives the id from the URL let id = req.params.id; findPostById(id, (post, err)=>{ if(err){ console.log(err); } else{ res.send(post) } }) }) let findPostById = (id, cb)=>{ console.log(id, 'Correctly receive the id'); let post = posts.find((post)=>{ return post.id === id; }) // Throws: 'TypeError: Cannot read property id of undefined' console.log(post.id); if(post){ cb(post, null); } else{ cb(null, new Error('Could not find post', id)); } }
The Fix
The root issue is a type mismatch: post.id in your posts array is a number, but req.params.id from the URL is always a string. The strict equality check (===) fails because the types don’t match, so find() returns undefined.
Convert the string ID to a number in your find callback, and add a check for post existence before accessing its properties:
let findPostById = (id, cb)=>{ console.log(id, 'Correctly receive the id'); let post = posts.find((post)=>{ // Convert string id to number using the unary plus operator return post.id === +id; }) // Check if post exists before accessing its properties if(post){ console.log(post.id); cb(post, null); } else{ cb(null, new Error(`Could not find post with id: ${id}`)); } }
This ensures the ID comparison uses matching types, so find() will correctly locate the post, and we avoid the TypeError by verifying post exists before accessing post.id.
内容的提问来源于stack exchange,提问作者M Masood

