Subdirectories not being served with express.static in heroku

一笑奈何 提交于 2019-12-05 02:52:58

问题


I'm seeing some really odd behavior where some of my files are correctly being returned by my express/node server (using express.static()), but not files within subdirectories. The frustrating thing is that it works fine using node or foreman locally, it just won't work on heroku. This gist has the main files at play here, and my app structure looks like this:

-app
    - index.html
    - img/
        - base.png
        - sub/
            - sub.png
    - scripts
        - base.js
        - sub/
            - sub.js
    - css
        - base.css
        - sub/
            - sub.css
- server
    - app.js

The index.html, and base.* files all load fine, it's just the sub.* files that 404. Seems bizarre that express.static would go 1 level deep, but not 2

I've tried a slew of different configurations, including this stackoverflow answer. I have to be missing something simple. Thanks for the help.

UPDATE:

When I console.log the following on server startup on heroku, I get:

  • path.join(__dirname, '../app') = /app
  • path.join(__dirname, '/../app') = /app/app
  • path.normalize(path.join(__dirname, '../app')) = /app/app
  • path.join(process.cwd(), '../app') = /app/app

回答1:


Make sure that the sub directories of your directory are added to your Git repository.

You can use heroku run 'ls ~' to help debug the issue (by observing the files on the dyno).

Putting the absolute path did not fix it for me. Your .gitignore may be excluding it.




回答2:


Try changing your static dir to :

app.use(express.static(path.join(__dirname, '/../app'), { maxAge: 86400000 }));

or

app.use(express.static(path.normalize(path.join(__dirname, '../app')), { maxAge: 86400000 }));



回答3:


add {{__dirname}}

<link href="{{__dirname}}/stylesheets/style.css" type="text/css" rel="stylesheet" media="screen,projection"/>

in your layout.hbs or layout.jde




回答4:


I've just had the same issue, and I've read all the different answers, some of which may have been important, but, in the end, this is the change I made after which the static content started getting served.

CALENDARSPATH = path.join(process.env.PWD, 'calendars');

...

-app.use(express.static(CALENDARSPATH, { maxAge: 86400000 }));
+app.use('/calendars', express.static(CALENDARSPATH, { maxAge: 86400000 }));


来源:https://stackoverflow.com/questions/19308792/subdirectories-not-being-served-with-express-static-in-heroku

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