Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 324
Tyler Avatar asked Jan 04 '16 18:01

Tyler


2 Answers

Use it this way:

app.use('/', express.static(__dirname + '/public'));
app.use('/orgprofile', express.static(__dirname + '/public'));
like image 141
Vikram Tiwari Avatar answered Sep 18 '22 23:09

Vikram Tiwari


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">
like image 39
fatdag Avatar answered Sep 22 '22 23:09

fatdag