Ajax POST请求内容无法送达服务器,请求正常但数据丢失求助
Hey there! Let's figure out why your server's logging an empty {} instead of your POST data—this is one of the most common pitfalls with Ajax requests, so let's walk through the key fixes:
1. You're Missing the Content-Type Request Header
Ajax requests don't always send the right Content-Type header by default, and servers rely on this to know how to parse incoming data.
- If you're sending JSON data, you need to explicitly set
Content-Type: application/json. Here's how that looks with jQuery:$.ajax({ url: "/your-server-endpoint", method: "POST", contentType: "application/json", // Critical line! data: JSON.stringify({ username: "emy", message: "hello" }), success: (res) => console.log(res) }); - For form data (like traditional HTML form submissions), use
Content-Type: application/x-www-form-urlencoded(or let the browser auto-set it if you useFormData).
2. Your Data Isn't Properly Serialized
Sending raw JavaScript objects directly won't work—you need to convert them into a format the server understands:
- For JSON: Use
JSON.stringify()to turn your object into a JSON string (like the example above). - For form data: Either format it as
key1=value1&key2=value2, or use the browser'sFormDataAPI to handle serialization automatically:const formData = new FormData(); formData.append("username", "emy"); formData.append("message", "hello"); const xhr = new XMLHttpRequest(); xhr.open("POST", "/your-server-endpoint"); xhr.send(formData); // No need to set Content-Type here—browser does it for you
3. Your Server Isn't Set Up to Parse the Data Format
Even if you send the data correctly, your server needs to be configured to parse the incoming request body:
- If you're using Node.js/Express, make sure you're using the right middleware:
- For JSON data: Add
app.use(express.json())before your route handlers. - For form data: Add
app.use(express.urlencoded({ extended: true })).
Example:
const express = require("express"); const app = express(); // Parse JSON request bodies app.use(express.json()); app.post("/your-server-endpoint", (req, res) => { console.log(req.body); // Now this will show your data instead of {} res.send("Data received!"); }); - For JSON data: Add
- For other server frameworks (like Django, Rails, etc.), double-check that you've enabled parsing for the content type you're sending.
Start by verifying these three areas—9 times out of 10, the issue is one of these mismatches between client-side formatting and server-side parsing.
内容的提问来源于stack exchange,提问作者Emy eminescu

