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

如何在Express.js中无需重复配置路由添加页面?含审核队列需求

Hey there! Let's tackle your questions about your Express.js site one by one.

1. Adding pages without manually updating index.js routes

You've got a couple of solid options here, depending on whether you're letting users upload Jade files or submit form content:

Option 1: Dynamic route matching for Jade templates

Set up a wildcard route that automatically looks for and renders Jade templates in your views directory based on the request URL. This way, any new Jade file you add to views will be accessible immediately without touching your route config.

Here's a quick implementation:

const fs = require('fs');
const path = require('path');

// Match any top-level page URL (e.g., /about, /contact)
app.get('/:page', (req, res) => {
  const pageSlug = req.params.page;
  const templatePath = path.join(__dirname, 'views', `${pageSlug}.jade`);

  // Check if the template exists first
  fs.access(templatePath, fs.constants.F_OK, (err) => {
    if (err) {
      return res.status(404).render('404'); // Fallback to 404 page
    }
    // Render the matching Jade template
    res.render(pageSlug);
  });
});

// If you need subdirectories (e.g., /blog/post-1), use a catch-all route
app.get('/:page*', (req, res) => {
  const fullPath = req.params.page + req.params[0];
  const templatePath = path.join(__dirname, 'views', `${fullPath}.jade`);
  
  fs.access(templatePath, fs.constants.F_OK, (err) => {
    if (err) return res.status(404).render('404');
    res.render(fullPath);
  });
});

Just make sure to place this wildcard route after any specific static routes (like /login or /dashboard) so those don't get overridden.

Option 2: Store page content in a database (better for form submissions)

If you're letting users submit page content via forms, storing pages in a database (like MongoDB, PostgreSQL) is more scalable—plus it makes adding an approval queue later way easier.

Here's a simplified example using MongoDB:

// First, define a Page schema (using Mongoose)
const pageSchema = new mongoose.Schema({
  slug: { type: String, required: true, unique: true },
  content: { type: String, required: true }, // Store Jade code or compiled HTML
  isPublished: { type: Boolean, default: false }, // Use this for future approval
  createdAt: { type: Date, default: Date.now }
});
const Page = mongoose.model('Page', pageSchema);

// Dynamic route to fetch and render pages
app.get('/:slug', async (req, res) => {
  try {
    // Only fetch published pages (you can adjust this for drafts later)
    const page = await Page.findOne({ slug: req.params.slug, isPublished: true });
    
    if (!page) {
      return res.status(404).render('404');
    }

    // If storing Jade code, compile it on the fly
    const jade = require('jade');
    const compiledTemplate = jade.compile(page.content);
    res.send(compiledTemplate());

    // Alternatively, pre-compile Jade to HTML when saving the page for better performance
    // res.send(page.content);
  } catch (err) {
    console.error(err);
    res.status(500).send('Oops, something went wrong!');
  }
});

This approach lets you easily add an approval queue later—just add an isApproved field, and only show pages where both isApproved and isPublished are true. You can build a simple admin dashboard to review and approve pending pages.

2. Will adding lots of pages slow down the site?

Short answer: Probably not, if you set things up right. Here's why:

  • For Jade template files: Node.js caches compiled Jade templates after the first render, so subsequent requests for the same page are fast. Even with hundreds of templates, the only minor hit is the first time each template is accessed (since it has to read from disk and compile it).
  • For database-stored pages: As long as you index the slug field in your database, queries will be lightning fast even with thousands of pages. For extra performance, add a caching layer (like Redis) to store the most popular pages' HTML content—this cuts down on database calls entirely for those pages.
  • Express route efficiency: Wildcard routes are processed efficiently by Express. Just make sure to order your routes correctly (specific routes first, wildcard last) to avoid unnecessary matching.

The main thing to watch out for is memory usage if you're compiling hundreds of Jade templates at once, but this is rarely an issue for most sites.

Hope this helps you move forward with your project!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:01:25