JavaScript中window.fetch发送POST请求时请求体为空的问题
Hey there! Let's figure out why your POST request body is showing up empty—this is a super common issue, and we can fix it with a few quick checks. Here are the most likely culprits and how to resolve them:
1. Missing or Incorrect Content-Type Header
Servers rely on the Content-Type header to know how to parse your request body. If you're sending JSON (the most common case), you must set this header to application/json. Without it, many servers will ignore the body entirely.
Correct Fetch Example:
const data = { key: "value", anotherKey: "anotherValue" }; fetch("your-target-url", { method: "POST", headers: { "Content-Type": "application/json", // This line is critical! // Add any other headers (like Authorization) here }, body: JSON.stringify(data) // Convert JS object to JSON string }) .then(response => response.json()) .catch(error => console.error("Request error:", error));
Correct XMLHttpRequest Example:
const xhr = new XMLHttpRequest(); const data = { key: "value" }; xhr.open("POST", "your-target-url"); xhr.setRequestHeader("Content-Type", "application/json"); // Don't skip this! xhr.onload = function() { if (xhr.status >= 200 && xhr.status < 300) { console.log("Success!", xhr.responseText); } else { console.error("Error:", xhr.statusText); } }; xhr.send(JSON.stringify(data)); // Send the stringified JSON
2. Forgetting to Stringify JSON Data
If you pass a plain JavaScript object directly as the body (instead of converting it to a JSON string), most browsers will automatically convert it to FormData—which might not match what your server expects, leading to an empty body from the server's perspective. Always use JSON.stringify() for JSON payloads.
3. Accidentally Using GET Instead of POST
Double-check that you're explicitly setting the method to "POST". GET requests don't support a request body, so if you accidentally use GET, your body will be ignored entirely.
4. Verifying the Request in DevTools
Before blaming your code, confirm the body is actually being sent:
- Open your browser's Developer Tools (F12 or Ctrl+Shift+I)
- Go to the Network tab
- Trigger your request
- Click on the request in the list to view details
- Check the Payload or Request Body section—if it's empty here, the issue is definitely on the client side. If it shows your data, the problem might be with the server's parsing logic.
Bonus: Sending Form Data
If you're submitting form data instead of JSON, use FormData (browsers usually set the correct Content-Type automatically for this):
const formData = new FormData(); formData.append("username", "johndoe"); formData.append("email", "john@example.com"); fetch("your-target-url", { method: "POST", body: formData }) .then(response => response.json()) .catch(error => console.error("Error:", error));
Give these fixes a try—9 times out of 10, it's one of these issues causing the empty body. Let me know if you're still stuck after checking these!
内容的提问来源于stack exchange,提问作者NavMen

