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

Node.js Express GET请求报循环结构转JSON错误问题排查

Fixing "TypeError: Converting circular structure to JSON" in Express GET Route

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 09:28:16