我有一个使用Jade模板引擎的Node.JS / Express应用程序。我的Javascript文件位于包含我的Jade视图的views目录上方的目录中。给定下面的代码,我认为该视图应该能够找到名为的 引用的服务器端Javascript文件common_routines
,但是当请求该视图时,出现404错误,提示找不到外部Javascript文件。这让我感到困惑,因为我认为Jade模板执行服务器端,那么为什么这会触发404 error
Jaderender()
调用?
这是翡翠视图:
block content
script(src="../common_routines.js")
div(style="padding:5px")
h4 #{product.name}
if (product.brand != null)
p Brand: #{product.brand}
div(class="img_and_desc")
img(src=product.imageUrl, class="product_image", align="left")
if (product.minimumPrice == product.maximumPrice)
p Price: #[strong #{product.minimumPrice}]
else
p Price: #[strong #{product.minimumPrice}] to #[strong #{product.maximumPrice}]
if (product.cashBack > 0)
p Cash Back amount: #[strong #{product.cashBack}]
if (product.freeShipping)
p(class="text-emphasized-1") *Free Shipping!
if (product.onSale)
p(class="text-emphasized-2") Discounted Item
这是渲染视图的路由文件中的调用的片段,在该视图if (err)
中触发了分支:
res.render(
'ajax-product-details',
locals,
function (err, html) {
if (err)
// A rendering error occurred.
throw new Error("Rendering error(type:" + err.type + ", message: " + err.message);
else {
// Success. Send back the rendered HTML.
res.send(html);
return;
}
});
这是我在WebStorm调试器控制台窗口窗格中看到的错误。请注意,尽管在Jade文件引用中可以清楚地看到前面的“ ..”相对目录引用,但是它将文件引用显示为/common_routines.js, 而没有前面的“ ..”相对目录引用。("script(src="../common_routines.js")):
[Express][127.0.0.1][GET][DESKTOP] 2016-07-20T10:07:34.940Z /common_routines.js?_=1469009245957
(development error handler) Status code(404) message: Not Found
这是common_routines.js的内容:
function truncateString(str, maxLen)
{
if (str.length > maxLen)
return str.substring(0, maxLen - 1) + '&hellip';
return str;
}
module.exports =
{
truncateString: truncateString
}
就像我说的那样,common_routines.js位于Jade视图上方的目录中,因此出于某种原因,此外部文件引用无效吗?:
script(src="../common_routines.js")
您只能public
在前端引用文件夹中的静态文件(如果已将静态资产设置为从该文件夹提供)。您可以将common_routines.js
文件放在公共目录下的文件夹中public/js/
。现在,您可以在视图文件中使用script(src="/js/common_routines.js")
如果您想在jade文件中使用这些功能,而不是在前端js文件中使用,则需要var commonRoutines = require('../common_routines.js');
在服务器端js文件内部使用该功能作为一个软件包包括在内。现在,您可以将此对象变量与上下文对象一起传递到视图文件。如前所述,在渲染时将locals对象传递给视图文件,您可以像这样进行操作:
var common_routines = require('../common_routines.js');
var locals = { common_routines: common_routines };
res.render( 'ajax-product-details', locals);
现在,你可以使用函数common_routines.js
在ajax-product-details
文件中。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句