![](/img/trans.png)
[英]What is the difference between “views” path and the path used in express.static?
[英]What is the rule for express.static root path?
我跑了
node src/app.js
在均值目錄中
express.static('public')
會工作,為什么呢?
不需要指定路徑?
有什么規則?
而且我知道
__dirname+'/../public'`
效果很好。
只想確保這里的邏輯
我在http://expressjs.com/en/starter/static-files.html上查找了文檔
它說
“將包含靜態資產的目錄的名稱傳遞給express.static中間件函數,以開始直接提供文件。”
“您提供給express.static函數的路徑是相對於您啟動節點進程的目錄的 ”
這是否意味着
為了安全起見,最好使用__dirname獲取目錄的絕對路徑
Express static使用模塊path
resolve函數
使用path
示例:
var p = require('path');
p.resolve('public'); // will return your absolute path for `public` directory
因此,用於表達靜態的規則與用於path#resolve
函數的規則相同
您可以在文檔中查看路徑模塊的更多示例
p.resolve
和__dirname
什么__dirname
?
p.resolve()
解析為絕對路徑
path.resolve('public');
將返回public
'目錄的絕對路徑(例如“ C:\\projects\\myapp\\public
”)
path.resolve('src'); // => "C:\projects\myapp\src")
__dirname
您當前從中運行應用程序的目錄名稱(絕對路徑)
文件app.js
console.log(__dirname);
運行node app.js
將為您的應用程序打印您的絕對路徑,例如“ C:\\projects\\myapp
”
您將兩行混合在一起...兩者都是必要的:
//This line is to say that the statics files are in public
app.use(express.static(__dirname + "/public"));
//This another line is to say that when call the route "/" render a page
app.get("/", function (req, res) {
res.send('Hello World!');
}
可能是因為在目錄中使用代碼比dir從目錄更高一級運行它? 嘗試從src運行它:
cd src
node app.js
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.