简体   繁体   English

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

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

This is my code from my index.js file (using express for routing) 这是我的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;

And this is my code from my index.jade 这是我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 is a variable that is defined in app.js and then used in my index.js file. source是在app.js中定义的变量,然后在我的index.js文件中使用。 I know this variable has a value because it prints to console.log when I start my application. 我知道此变量有一个值,因为启动我的应用程序时它将打印到console.log。 However the image does not load and instead displays a 404 question mark. 但是,该图像不会加载,而是显示404问号。

If I copy and paste the image source (which is: http://naccrra.org/sites/default/files/default_site_pages/2013/instagram-icon.png ) then the image loads fine. 如果我复制并粘贴图像源(即: http : //naccrra.org/sites/default/files/default_site_pages/2013/instagram-icon.png ),则图像可以很好地加载。

What am I doing wrong here? 我在这里做错了什么?

Thank you in advance for your help. 预先感谢您的帮助。

You were accepting an argument with the same name that the varible from outer scope has and which you intended to use - source 你被接受与从外部范围varible有和您打算使用相同名称的参数- source

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

Any named argument to a function takes precedence over the same name variable of the outer scope. 函数的任何命名参数优先于外部作用域的相同名称变量。 For example: 例如:

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

If no variable was passed when calling, but the definition still takes a named argument, that argument will automatically be undefined , which is what was happening in your case. 如果在调用时未传递任何变量,但定义仍使用命名参数,则该参数将自动为undefined ,这就是您所遇到的情况。 collection.find 's callback is only ever called with two arguments - e and docs , any sunsequent arguments if named would have been set to undefined 仅使用两个参数( edocs调用collection.find的回调,任何后续的参数(如果命名)将被设置为undefined

You simply needed not take that extra named argument, which was unnecessary in the first place. 您只需不需要使用额外的命名参数,而这首先是不必要的。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM