Node.js Express GET请求报循环结构转JSON错误问题排查
Great catch identifying the route conflict as the root cause! Here's a detailed breakdown of why this happens and how to resolve it cleanly:
Why the Error Occurs
Express matches routes in the order they're defined. Your /:skip/:talk route is a generic parameterized route that will catch any two-segment path—including requests meant for /info/:book_id (where info gets treated as the skip parameter and book_id as talk).
When the request lands in the wrong route handler, it's likely returning an object with circular references (like accidentally passing req or res to res.send(), which have internal cross-references). Express tries to serialize this to JSON, triggering the Converting circular structure to JSON error. Your POST/DELETE routes work because they don't overlap with the generic route pattern.
Step-by-Step Fix
1. Reorder Your Routes
Always define specific routes first, before generic parameterized routes. This ensures exact matches are caught before generic ones:
// Define the specific book info route FIRST router.get('/info/:book_id', function (req, res) { Book.findById(req.params.book_id, (err, book) => { if (err) return res.status(500).send(err); res.status(200).send(book); }); }); // Then define your generic parameter route router.get('/:skip/:talk', function (req, res) { // Your existing logic for this route });
2. Optional: Safeguard Mongoose Document Serialization
While not the issue here, adding a toJSON transform to your Mongoose schemas can prevent future serialization issues by cleaning up the document before it's sent as JSON:
For your Book schema:
const book = mongoose.Schema({ _id: mongoose.Schema.Types.ObjectId, title: {type: String, required: true}, author: {type: mongoose.Schema.Types.ObjectId, ref: 'User'}, sinopsis: {type: String, required: true}, text: {type: mongoose.Schema.Types.ObjectId, ref: 'Text'}, creation_date: {type: Date, default: Date.now}, cover: {type: String}, coments: [coment], votes: [vote] }, { toJSON: { transform: (doc, ret) => { // Remove internal Mongoose fields delete ret.__v; // Ensure no circular references (though Mongoose handles this by default) return ret; } } });
This ensures the Book document is properly serialized without extra fields or unexpected references.
内容的提问来源于stack exchange,提问作者Dmyto Holota

