Express中将Angular通过FormData发送的JSON字符串转为对象的方法
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.
- Install it via npm:
npm install he - 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

