【发布时间】:2016-07-20 10:18:43
【问题描述】:
我有一个使用 Jade 模板引擎的 Node.JS/Express 应用程序。我的 views 目录正上方的目录中有一个 Javascript 文件,其中包含我的 Jade 视图。鉴于下面的代码,我相信视图 应该 能够找到引用的服务器端 Javascript 文件,名为 common_routines,但是当请求视图时,我得到一个 404错误提示找不到外部 Javascript 文件。这让我很困惑,因为我认为 Jade 模板执行服务器端,那么为什么这会触发 Jade render() 调用中的 404 error?
这是翡翠视图:
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
这是来自渲染视图的路由文件的调用的 sn-p,其中触发了 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 调试器控制台窗口窗格中看到的错误。请注意,它将文件引用显示为 /common_routines.js 没有前面的“..”相对目录引用,尽管前面的“..”相对目录引用是在 Jade 文件参考中清晰可见 ("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")
【问题讨论】:
-
您在
app.js文件中为您的公共资产设置了什么路径? -
@MohitBhardwaj - app.use(express.static(path.join(__dirname, 'public')));但是 common_routines.js 或引用该文件的视图都不在该目录树中。
标签: javascript node.js express pug