Node.js/JSON问题:设置值时出现[object Object]而非预期值
[object Object] Instead of Expected Values Hey there, let's break down why your small API's POST requests are ending up with [object Object] instead of the values you set, and how to fix it.
The Root Cause
That [object Object] string is what you get when JavaScript tries to convert an object to a string using the default toString() method. This usually happens when you're passing an object somewhere that expects a string, or when the request package isn't configured to handle your payload correctly.
Let's Fix Your Code
Looking at your setup with the request package, here are the key fixes you need:
1. Send JSON Payloads Properly
If you're trying to send a JSON body (the most common use case for APIs), you need to tell the request package to handle JSON serialization for you. Add the json: true flag to your request config, and use the body field instead of form:
request.post({ url: yourTargetUrl, json: true, // This tells request to serialize your object to JSON body: { // Your actual payload object here key1: "value1", key2: { nestedKey: "nestedValue" } // This won't turn into [object Object] now } }, (error, response, body) => { // Handle your response here });
The json: true flag does two important things:
- Automatically converts your JavaScript
bodyobject to a JSON string - Sets the correct
Content-Type: application/jsonheader for the request
2. If You Need Form Data (application/x-www-form-urlencoded)
If you're sending form data instead of JSON, make sure all values are strings or basic types. If you have nested objects, you'll need to stringify them manually with JSON.stringify():
request.post({ url: yourTargetUrl, form: { plainKey: "plainValue", nestedKey: JSON.stringify({ nested: "object" }) // Manually convert nested objects } }, (error, response, body) => { // Handle response });
3. Double-Check Commander Parameter Handling
Since you're using Commander for CLI args, make sure any parameters you're passing into the request body are parsed correctly. If you're accepting JSON strings from the command line, parse them into objects first with JSON.parse() before adding them to your payload:
const parsedArg = JSON.parse(commander.yourArg); // Don't pass the raw string directly
Quick Debugging Tip
Before sending the request, log your payload to make sure it's structured how you expect:
const payload = { /* your payload */ }; console.log("Payload to send:", payload); console.log("Type of payload:", typeof payload);
This will help you catch if something's already an unexpected string or malformed object before it gets sent.
内容的提问来源于stack exchange,提问作者Zeay

