Tyler
Tyler

Reputation: 1891

Express.Static not working for subdirectory

Express.static is working great for any view in root directory, but it breaks when I add a subdirectory.

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

Works:

//Homepage
router.get('/', isAuthenticated, function (req, res, next) {
    res.render('index.hbs', {user: req.user, message:req.flash('message')});      //add add'l data {title:'Express', addlData:'SomeData', layout:'layout'}
});

Doesn't Work:

//Organization Profile
router.get('/orgprofile/:username', function(req,res,next){
    User.findOne({username:req.params.username}, function(err,docs){
        res.render('orgprofile.hbs',{orgdetails:docs});
    });
});

I'm guessing __dirname is changed to whatever directory the get request is made from, but I just want to use the root (/public) directory for all static requests.

Upvotes: 9

Views: 17121

Answers (4)

Emile
Emile

Reputation: 1

I have used this :

appRouter.all('/*', (req, res) => { res.sendFile('public'.concat(req.path), { root: process.cwd() }); });

Upvotes: 0

Herman Van Der Blom
Herman Van Der Blom

Reputation: 802

I had the same problem. If I use an URL like http://localhost:8080/postcreate/personal it would fail because of wrong value of __dirname. The URLs in the layout file for css, js files or image sources get the wrong prefix. I did solve this by using: proces.env.PWD instead. Now its always using the project folder and that's what I want. The project folder is my root. Same like .NET projects work. The problem with me was that I set express.static in a seperate app folder.

Upvotes: 0

fatdag
fatdag

Reputation: 131

Problem is not caused by express.static() expression. It might be due to wrong href value. express.static():

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

Reference:

<link rel="stylesheet" type="text/css" href="/stylesheets/main.css">

Upvotes: 4

Vikram Tiwari
Vikram Tiwari

Reputation: 3895

Use it this way:

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

Upvotes: 15

Related Questions