Javascript express.static()不提供路由器路径中的公用文件夹中的文件,这些路径不是/&引用;
Express.static配置:Javascript express.static()不提供路由器路径中的公用文件夹中的文件,这些路径不是/&引用;,javascript,node.js,express,ejs,Javascript,Node.js,Express,Ejs,Express.static配置: app.use(express.static(__dirname + "/public")); 文件结构: --public --assets --js --[js scripts] --stylesheets --[css files] 路线: const shopRoutes = require('./routes/shopRoutes') app.use('/', shopRoutes) const itemApiRou
app.use(express.static(__dirname + "/public"));
文件结构:
--public
--assets
--js
--[js scripts]
--stylesheets
--[css files]
路线:
const shopRoutes = require('./routes/shopRoutes')
app.use('/', shopRoutes)
const itemApiRoutes = require('./routes/itemApiRoutes')
app.use('/api/shopitems', itemApiRoutes)
const logSignRoutes = require('./routes/logSignRoutes')
app.use('/account', logSignRoutes)
问题是“localhost:3000/”(shopRoutes)根路径中的所有ejs文件都会像这样调用以下css文件,并且工作得非常好:
<link rel="stylesheet" type="text/css" href="stylesheets/header.css">
我是否不了解express.static如何服务于静态文件,或者我是否做了一些不正确的事情?如果您指定了一个相对URL,例如:
href="stylesheets/header.css"
然后浏览器将您所在网页的路径添加到该路径中,并从服务器请求该组合路径。除非您的网页位于网站的顶层,因此没有路径,否则它将无法正常工作。我想强调的是,这是浏览器在做这件事,而不是表达。因此,如果您在具有此URL的网页中:
http://localhost:3000/account/login
并且,浏览器会看到:
<link rel="stylesheet" type="text/css" href="stylesheets/header.css">
使用
标记中的相对URL,如您所知,它将请求:
/account/login/stylesheets/header.css
当,express.static()
__dirname + "/public"
目录层次结构,因此将找不到它
相反,您希望指定一个前导斜杠:
<link rel="stylesheet" type="text/css" href="/stylesheets/header.css">
当express.static()
__dirname + "/public"
最终会找到一个文件
__dirname + "/public" + "/stylesheets/header.css"`
这将在您的公用目录层次结构中找到,并将起作用。非常感谢!我不知道斜杠有多重要。为了确保我理解这一点,url“someurl”中“/folder/file”的前导斜杠表示“嘿,服务器,我要检查根目录中的文件夹“folder”,然后获取“file”。相反,没有前导斜杠会说,“嘿,url,给我“url/folder/file”@QuanCao-Yep中的“file”,这个小斜杠告诉浏览器在请求url之前是否添加包含网页的路径。
/stylesheets/header.css
__dirname + "/public"
__dirname + "/public" + "/stylesheets/header.css"`