如何在HTTP请求中传递POST数据?代码执行遇body参数读取失败错误
Hey there, let's sort out this POST data issue you're hitting. That error message makes it clear: the server expects a JSON-formatted request body that includes a required requestType parameter, but your current request isn't sending that correctly. Let's break down how to fix this across common tools and languages:
If you want to verify the API works first, use curl to send a properly formatted JSON request:
curl -X POST \ https://your-api-endpoint.com/target-path \ -H "Content-Type: application/json" \ -d '{ "requestType": "your-specific-type", "optionalParam": "any-extra-data" }'
Key notes here:
- The
-Hflag sets theContent-Typeheader toapplication/json—this tells the server to parse the body as JSON. - The
-dflag contains your JSON payload, which must include therequestTypefield with a valid value.
If you're using Python, the requests library makes this straightforward. Here's the correct approach:
import requests url = "https://your-api-endpoint.com/target-path" payload = { "requestType": "your-specific-type", # Add any other required parameters here } # The `json=payload` argument automatically sets the Content-Type header to application/json response = requests.post(url, json=payload) print("Status code:", response.status_code) print("Response:", response.json())
Avoid the common mistake of using data=payload without converting it to JSON first—using json=payload handles serialization and headers for you.
For front-end code, use fetch to send a JSON POST request like this:
const apiUrl = 'https://your-api-endpoint.com/target-path'; const requestBody = { requestType: 'your-specific-type', // Include other parameters as needed }; fetch(apiUrl, { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(requestBody), }) .then(response => response.json()) .then(data => console.log('Success:', data)) .catch(error => console.error('Error:', error));
Important: You must use JSON.stringify() to convert your JavaScript object into a JSON string, and explicitly set the Content-Type header.
- Missing Content-Type header: Without
application/json, the server won't parse your body as JSON, so it can't findrequestType. - Invalid JSON syntax: Make sure you use double quotes for keys/values (JSON doesn't allow single quotes) and fix any missing commas or brackets.
- Typos in
requestType: The parameter name is case-sensitive—double-check you're using the exact spelling the server expects (e.g., notRequestTypeorrequesttype). - Using form data instead of JSON: If you're sending
application/x-www-form-urlencodeddata, the server won't look for JSON fields likerequestType.
内容的提问来源于stack exchange,提问作者Nevis Franko

