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

React+Axios POST请求为空问题求助(Node.js/Express后端)

Hey there! Let's figure out why your POST request is sending empty data to the backend. From what you described, the core issue is that your React frontend isn't properly formatting the form data to match what your Node/Express backend expects (application/x-www-form-urlencoded), which is causing Sequelize to throw validation errors or save null values. Here's how to fix this step by step:

1. Fix Your Axios POST Request Format

Axios defaults to sending data as JSON (Content-Type: application/json), but your backend requires application/x-www-form-urlencoded. You need to serialize your form data correctly and set the right header:

Option 1: Use URLSearchParams (no extra libraries needed):

// In your ProductNew.js component
import axios from 'axios';
import { useState } from 'react';

const ProductNew = () => {
  const [title, setTitle] = useState('');
  const [description, setDescription] = useState('');
  const [price, setPrice] = useState('');

  const handleSubmit = async (e) => {
    e.preventDefault();
    try {
      const formData = new URLSearchParams();
      formData.append('Title', title);
      formData.append('Description', description);
      formData.append('Price', price);

      const response = await axios.post('/api/products', formData, {
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded'
        }
      });
      console.log('Product added:', response.data);
      // Reset form or redirect here
    } catch (err) {
      console.error('Error adding product:', err);
    }
  };

  return (
    <form onSubmit={handleSubmit}>
      <input type="text" value={title} onChange={(e) => setTitle(e.target.value)} placeholder="Title" required />
      <textarea value={description} onChange={(e) => setDescription(e.target.value)} placeholder="Description" required />
      <input type="number" value={price} onChange={(e) => setPrice(e.target.value)} placeholder="Price" required />
      <button type="submit">Add Product</button>
    </form>
  );
};

export default ProductNew;

Option 2: Use the qs library (for cleaner syntax):
First install the library:

npm install qs

Then update your request logic:

import qs from 'qs';

// Inside handleSubmit
const data = { Title: title, Description: description, Price: price };
const response = await axios.post('/api/products', qs.stringify(data), {
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
  }
});

2. Verify Your Backend's Body Parser Middleware

Make sure your Express app is configured to parse application/x-www-form-urlencoded data. Add this line before your routes:

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

// This parses x-www-form-urlencoded data (critical for your POST requests)
app.use(express.urlencoded({ extended: true }));

// Your product routes here
app.use('/api/products', productRoutes);

Without this middleware, req.body will be empty, which directly causes the validation errors or null values you're seeing.

3. Check Field Name Consistency

Double-check that the field names in your frontend request match exactly what your Sequelize model expects. Your model uses Title, Description, Price (capitalized), so your frontend must send those exact keys. If you accidentally use lowercase (like title instead of Title), your backend won't pick up the values, leading to nulls.

4. Validate Frontend Form State

Ensure your form inputs are correctly bound to state variables. If the onChange handlers aren't updating the state, you'll send empty strings or undefined values to the backend. Test this by logging the state variables right before sending the request:

console.log('Sending data:', title, description, price);

If any of these are empty, fix your input bindings to ensure state updates correctly.

Once you make these changes, your POST request should send the correct data to the backend, and Sequelize will validate and save the product without errors.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 03:30:53