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

Node.js Express:未传数据时res.render()仍生成带数据HTML的问题

Hey there! Let's dig into those weird template rendering quirks you're hitting while working through Getting MEAN With Mongo, Express, Angular, and Node—I've tangled with similar issues before, so let's break this down step by step.

First, Let's Recap Your Issues

From what you described:

  1. When calling res.render() without passing any data, your app still generates HTML with data (that shouldn't be there)
  2. When you pass the correct data to res.render(), your Jade template throws errors depending on how you structure the markup

Let's Walk Through Code & Fixes

First, I'll assume your code looks something like the snippets below (adjust if yours differs):

1. Route File: routes/locations.js

const express = require('express');
const router = express.Router();
const Location = require('../models/location');

// Problem 1: No data passed, but HTML still has content
router.get('/', function(req, res, next) {
  res.render('locations-list');
});

// Problem 2: Passing data causes Jade errors
// router.get('/', function(req, res, next) {
//   Location.find({}, (err, locations) => {
//     res.render('locations-list', { title: 'Local Spots', locations: locations });
//   });
// });

module.exports = router;

2. Main App File: app.js / index.js

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

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// Check for accidental global data injection here!
app.use((req, res, next) => {
  // If you have something like this uncommented, it'll leak data to all templates
  // res.locals.locations = [{ name: "Test Cafe", address: "123 Main St" }];
  next();
});

app.use('/', require('./routes/locations'));

app.listen(3000, () => {
  console.log('Server running on port 3000');
});

3. Jade Template: views/locations-list.jade

extends layout

block content
  h1= title
  ul.locations-list
    each location in locations
      li.location-item
        h2= location.name
        p= location.address

Fix for Issue 1: res.render() Without Data Still Shows Content

This almost always boils down to Express template caching or accidental global data injection:

  • Disable template caching (dev environment only)
    Express caches rendered templates by default to speed things up, but in development this causes old data to stick around even when you don't pass new data. Add this to your main app file:
    if (app.get('env') === 'development') {
      app.set('view cache', false);
    }
    
  • Check for global res.locals injection
    Any data added to res.locals becomes available to all templates automatically. Double-check your middleware in app.js—if you have code that sets res.locals.locations (even accidentally), that's where the stray data is coming from.

Fix for Issue 2: Errors When Passing Correct Data to Jade

Most Jade template errors here are due to mismatched data structures or syntax typos:

  1. Verify your data structure first
    Before rendering, log the data from your Mongo query to confirm it's what your template expects:
    Location.find({}, (err, locations) => {
      console.log('Fetched data:', locations); // Should be an array of objects with name/address fields
      res.render('locations-list', { title: 'Local Spots', locations: locations });
    });
    
    If locations is empty, undefined, or missing fields, your template will throw errors.
  2. Fix Jade syntax typos
    • Make sure your loop variable matches the data you're passing: if you pass locations (plural), your loop should be each location in locations (not each loc in location).
    • If you get "undefined property" errors, confirm the Mongo documents actually have the fields you're referencing (e.g., location.name exists in your database).
  3. Handle empty data gracefully
    Add a fallback in your template for when no locations exist, so it doesn't crash:
    block content
      h1= title
      if locations && locations.length > 0
        ul.locations-list
          each location in locations
            li.location-item
              h2= location.name
              p= location.address
      else
        p No locations found!
    

Quick Validation Steps

  1. Restart your server after disabling template cache
  2. Test the no-data res.render() again—should now show empty content (or your fallback message)
  3. Run the Mongo query route with console.log to confirm data shape, then adjust your template to match

内容的提问来源于stack exchange,提问作者Manics lie ohm

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:15:47