如何从 node.js 中的变量传递 jade 中的图像源

How to pass an image source in jade from a variable in node.js

这是我的 index.js 文件中的代码(使用 express 进行路由)

var express = require('express');
var router = express.Router();

/* GET home page. */
router.get('/', function(req, res){
   var db = req.db;
   var collection = db.get('usercollection');
   var source = req.app.get('imgSource');
   console.log("IMG SOURCE: " + source);
   collection.find({},{},function(e,docs,source){
     res.render('index',{
      "userlist" : docs,
      "imgURL" : source,
      "title": "Insta-Famous"
     });
   });
});

module.exports = router;

这是我 index.jade

的代码
extends layout

block content
 h1= title
 p Welcome to #{title}
 ul
  each user, i in userlist
    li
        p #{user.instaid}
        p #{user.price}
    li
        img(src = "#{imgURL}")

source 是在 app.js 中定义的变量,然后在我的 index.js 文件中使用。我知道这个变量有一个值,因为它在我启动我的应用程序时打印到 console.log。但是,图像未加载,而是显示 404 问号。

如果我复制并粘贴图像源(即:http://naccrra.org/sites/default/files/default_site_pages/2013/instagram-icon.png),则图像加载正常。

我做错了什么?

预先感谢您的帮助。

您正在接受一个与外部作用域的变量具有相同名称并且您打算使用的参数 - source

var source = req.app.get('imgSource');
collection.find({},{},function(e,docs,source){
 ...
});

函数的任何命名参数都优先于外部作用域的同名变量。例如:

var a = 1;
var b = 2;
function fn(a){
    a //=> 'precedence'
    b //=> 2
}
fn('precedence');

如果调用时没有传递变量,但定义仍然采用命名参数,则该参数将自动为 undefined,这就是您的情况。 collection.find 的回调仅使用两个参数调用 - edocs,任何后续参数如果命名将被设置为 undefined

您根本不需要采用那个额外的命名参数,这首先是不必要的。

var source = req.app.get('imgSource');
collection.find({},{},function(e,docs){
 ...
});