Express后端如何返回字符串,使客户端res.json()获JSON格式字符串而非对象
To make the client's res.json() return a string representation of your JSON object instead of a parsed JavaScript object, you need to send a JSON-serialized string from the backend. Here's how to do it:
Modified Backend Code
app.post('/api/verificationstart', (req, res) => { // Create your target response object const responseObj = { message: 'TEST' }; // Serialize the object into a JSON-formatted string const responseStr = JSON.stringify(responseObj); // Send this string as the JSON response return res.status(400).json(responseStr); });
Why This Works
The client's res.json() method automatically parses the response body into a JavaScript object. If you send a plain JSON object directly from the backend, res.json() will parse it into an object immediately.
By first serializing your object to a string with JSON.stringify(), then sending that string via res.json(), you're telling the backend to wrap the string in valid JSON formatting (adding quotes and escaping special characters). When the client calls res.json(), it parses this wrapped content and returns the original JSON string instead of a parsed object.
Why Your Previous Attempts Failed
res.send('"{ "message": "string" }"'): This sends invalid JSON (unescaped inner quotes), which would trigger parsing errors on the client.res.send('{ message: "test" }'): This sends invalid JSON (unquoted property name), sores.json()can't parse it correctly.res.send('{ "message": "test" }'): This sends valid JSON, butres.json()parses it into a JavaScript object instead of returning it as a raw string.
内容的提问来源于stack exchange,提问作者T THE R

