Express serve static files in nested directory

Deadly 提交于 2020-04-11 08:21:10

问题


I am not new to working with express and rendering template views but recently I tried a new directory structure which seems to have confused my app instance.

It no longer serves my static bootstrap, css and image files anymore and my view looks all messed up now.

Here's my directory structure

AppName
 - node_modules folder
 - src (all code live here)
        - public (statics)
             - css/mycss, bootstrapcss
             - js/ myjs, bootstrapjs
             - images folder
        - models
        - app.js (entry point)

The static files seem to be two levels deeper than the root directory. In my app.js file, I have tried using express static method like so:

app.use( express.static(path.join(__dirname, './src' + '/public')));

and also tried this:

app.use('/src', express.static(path.join(__dirname, '/public')));

In my views, for example the statics are called like this:

<link href="../public/css/bootstrap.css" rel="stylesheet" type="text/css">
<link rel="stylesheet" href="../public/fonts/glyphicons-halflings-regular.ttf">
<link rel="stylesheet" href="../public/css/styles.css" type="text/css">

<script defer src="https://use.fontawesome.com/releases/v5.0.8/js/all.js"></script>
<script src="https://cdn.ckeditor.com/ckeditor5/1.0.0-alpha.2/classic/ckeditor.js"></script>

but still unable to serve those files to my views. I'm stuck on this. Can someone help me out? Thanks


回答1:


Try this:

app.use(express.static(path.join(__dirname, 'src/public')));

And this:

<link href="/css/bootstrap.css" rel="stylesheet" type="text/css">
<link rel="stylesheet" href="/fonts/glyphicons-halflings-regular.ttf">
<link rel="stylesheet" href="/css/styles.css" type="text/css">


来源:https://stackoverflow.com/questions/49193085/express-serve-static-files-in-nested-directory

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