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

标签 javascript node.js express pug

这是我的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');

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

您只需不需要额外的命名参数,这本来是不必要的。

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

关于javascript - 如何从node.js中的变量传递jade中的图像源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31105248/

相关文章:

javascript - document.cookie : Works in localhost but Returns Empty on Web Hosting 问题

javascript - 使用 Promise 进行 fetch().then() 后页面保持刷新(设置了 e.preventDefault())

node.js - 使用 Jasmine 和 Express 模拟请求对象

javascript - 在音频播放器中添加缓冲条

javascript - 实时 API 后端和前端

javascript - Gatsby :在页面节点上调用 `touchNode` 抛出 'TypeError: locationAndPageResources.pageResources is undefined'

node.js - 如何仅将受影响的 nx 服务部署到 GCP APP Engine

javascript - 如何解决 Mongoose Connect UNKNOWN 问题?

javascript - 在输入更改和复选框更改时运行功能

javascript - 使用查询选择器 Alll 选择多个元素 - JavaScript