Issue with express static middleware and subdirectory

♀尐吖头ヾ 提交于 2020-01-05 04:22:20

问题


I have this folder as my website structure

-views
  -index
  -post
-public
  -css
  -js
  -images
-app.js

But a post link can be:

mywebsite.com/posts/a-link-example

So, when I use express static middleware like this:

app.use(express.static(__dirname + '/public'));

it only works in pages without a "subdirectory" like

example.com/home
example.com/contact

but not on

example.com/posts/post-name

I can use of course:

app.use('/posts, express.static(__dirname + '/public'));

but is there a better way to do it?


回答1:


Don't use relative paths to point to static resources (like scripts and stylesheets), use absolute paths:

<link rel="stylesheet" href="/css/style.css">



回答2:


You can change static asset links from:

<link rel="stylesheet" href="./css/style.css">

to:

<link rel="stylesheet" href="/css/style.css">


来源:https://stackoverflow.com/questions/43347578/issue-with-express-static-middleware-and-subdirectory

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!