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

Express中将Angular通过FormData发送的JSON字符串转为对象的方法

Fixing HTML-Escaped JSON Data from FormData in Express

Alright, let's break down what's happening here and how to fix it. The issue is that your JSON string is getting HTML-escaped when it hits your Express backend—those " values are just escaped double quotes. That's why JSON.parse() fails, even though console.dir() makes it look like valid data (console methods often auto-decode these entities for readability).

Step 1: Decode the HTML Entities First

Before you can parse the JSON, you need to convert those " back into regular double quotes. You have two easy options:

Option A: Use a Reliable HTML Decoding Library

The he library is a popular, lightweight choice for handling HTML entity decoding.

  1. Install it via npm:
    npm install he
    
  2. Use it in your Express route:
    const he = require('he');
    
    // Inside your route handler
    const encodedData = req.body.data;
    const decodedData = he.decode(encodedData);
    const parsedCollections = JSON.parse(decodedData);
    
    // Now parsedCollections is your original array of objects, ready to use!
    console.log(parsedCollections[0].description); // Should log "store"
    

Option B: Quick Manual Replacement (For Simple Cases)

If you don't want to add a new dependency, you can write a quick replacement function for the specific escaped character you're seeing:

function decodeQuotes(str) {
  return str.replace(/"/g, '"');
}

// Inside your route handler
const encodedData = req.body.data;
const decodedData = decodeQuotes(encodedData);
const parsedCollections = JSON.parse(decodedData);

Why This Happens

When you send FormData, Express typically uses the urlencoded parser from body-parser (or the built-in express.urlencoded() middleware). This parser automatically escapes HTML-special characters (like quotes) to prevent XSS vulnerabilities, which is why your JSON string gets mangled into " instead of ".

Bonus: Verify Your Backend Middleware Setup

Make sure you have the urlencoded middleware configured correctly in your Express app. It should look something like this:

const express = require('express');
const app = express();

// This ensures FormData is parsed correctly
app.use(express.urlencoded({ extended: true }));

内容的提问来源于stack exchange,提问作者Prachi Sharma

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 16:27:50