You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Express后端如何返回字符串,使客户端res.json()获JSON格式字符串而非对象

Solution

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), so res.json() can't parse it correctly.
  • res.send('{ "message": "test" }'): This sends valid JSON, but res.json() parses it into a JavaScript object instead of returning it as a raw string.

内容的提问来源于stack exchange,提问作者T THE R

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 07:46:12