You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React+Express/Node+MongoDB POST请求req.body为空问题排查

Hey, let's get this POST request working for you! There are two key issues causing your Express backend to receive an empty req.body and your form data to not sync properly. Here's how to fix them step by step:

1. Your Express backend isn’t parsing JSON request bodies

By default, Express doesn’t automatically parse JSON-formatted request bodies—this is exactly why req.body shows up as an empty {}. You need to add the express.json() middleware before defining your routes to handle JSON payloads correctly.

Fixed Express code:

const express = require('express');
const app = express();

// Critical: Add this middleware BEFORE your routes to parse JSON bodies
app.use(express.json());

app.post('/stored', (req, res) => {
  console.log(req.body); // Now this should log the correct form data!
  db.collection('quotes').insertOne(req.body, (err, data) => {
    if (err) return console.error(err);
    // Send a proper JSON response instead of a string + object (avoids parsing issues)
    res.json({ message: 'Saved to DB successfully', insertedData: data.ops[0] });
  });
});

2. Your React form inputs are incorrectly bound to state

You’re using this.nameIn and this.quoteIn for your input value props, but your form data is stored in the component’s state object—so you need to reference this.state.nameIn and this.state.quoteIn instead. Also, don’t forget to prevent the default form submission behavior (which refreshes the page) or you’ll miss seeing your console logs.

Fixed React code:

handleSubmit(event) {
  // Stop the form from reloading the page (critical for seeing logs)
  event.preventDefault();

  const databody = { 
    name: this.state.nameIn, 
    quote: this.state.quoteIn 
  };

  fetch('http://localhost:5002/stored', { 
    method: 'POST', 
    body: JSON.stringify(databody), 
    headers: { 
      'Content-Type': 'application/json' 
    }, 
  })
  .then(res => res.json())
  .then(data => console.log('Success:', data))
  .catch(err => console.error('Request error:', err)); // Add catch to debug failed requests
}

render() {
  return (
    <div>
      <form onSubmit={this.handleSubmit}>
        <label> 
          Name 
          <input 
            type="text" 
            name="name" 
            value={this.state.nameIn} 
            onChange={this.handleNameChange}
          /> 
        </label>
        <label> 
          Quote 
          <input 
            type="text" 
            name="quote" 
            value={this.state.quoteIn} 
            onChange={this.handleQuoteChange}
          /> 
        </label>
        <input type="submit" value="Add to DB" />
      </form>
    </div>
  );
}

Quick Extra Checks

Don’t overlook these easy-to-miss details that can break form state sync:

  • Initialize state in your component constructor:
    constructor(props) {
      super(props);
      this.state = {
        nameIn: '',
        quoteIn: ''
      };
      // Bind event handlers to avoid `this` context issues
      this.handleNameChange = this.handleNameChange.bind(this);
      this.handleQuoteChange = this.handleQuoteChange.bind(this);
      this.handleSubmit = this.handleSubmit.bind(this);
    }
    
  • Update state correctly in your change handlers:
    handleNameChange(event) {
      this.setState({ nameIn: event.target.value });
    }
    
    handleQuoteChange(event) {
      this.setState({ quoteIn: event.target.value });
    }
    

After making these changes, restart both your Express server and React app. Your form should now send data to the backend, and req.body will show the correct name/quote values that get inserted into MongoDB!

内容的提问来源于stack exchange,提问作者albert

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:41:27