简体   繁体   中英

ExpressJS Public Files Not Being Served Once Deployed (NodeJS/Express)

Project directory structure is as follows:

my_project
server.js
app.js
|
| - public
|           ----------| images | javascripts | stylesheets
|           -------------- imgs ---scripts.js ---styles.css 
|
| - routes
|
| - views
|           ----------| partials
|           -------------- header.ejs, searchbar.ejs, footer.ejs
| (rendered views.ejs)
|
| 
| misc. files

Within my header.ejs file, this is the path to my .css file located in public/stylesheets/style.css : href='/stylesheets/style.css'

Within my app.js file, here is my code telling express to serve the public directory: app.use(express.static(path.join(__dirname, 'public'))); . Additionally, I have also tried: app.use(express.static('/public')); but have not had any luck.

Currently both JS and CSS files are being served locally just fine, but when I deploy this application (and I have no control over the root directory or structure), it is not serving the files.

This is what I'm not sure how to handle -- locally, having the '/' in front of href='/stylesheets/style.css' works perfectly, but I know once deployed this is going to search the route of the domain and of course it's not going to be there. But, if I remove the '/' , it stops working locally but may serve the file correctly once deployed.

How do I fix this issue? Any advice would be appreciated.

I found a solution to my issue. For future searcher's who are experiencing the same issue, try setting up a dynamic path variable that you render via each route. For example:

My header.ejs file contains the following link to the .css file: <link rel='stylesheet' href='<%= path %>stylesheets/style.css'> .

You can then pass a specific path into your desired view.ejs via its corresponding router. For example, my index.js route contains something like this:

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', {  path: '' });
});

Since directory structure may vary from a local development environment to an actual production/testing server, doing this (if using a concept like a header partial) will allow you to dynamically serve your public assets. For example, the rendered path to another view via its corresponding route may look like this:

router.get('/newdirectory', function(req, res) {
  res.render("new-view", { path: '../' });        
});

This will allow you to modify your public assets (scripts, images, stylesheets), etc. depending on its location relative to the file being requested. Good luck!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM