Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Express 4: After redirect i can't get my static file

I'm having troubles with Express 4 and static files. After a successful login i redirect my web-app to '/home/userId' but then, i get 404 on all static files. This is my router:

router.get('/home/:userid', function(req, res, next) {
  // TODO check if token is valid
 User.findById(req.params.userid).exec(function(err, find) {
    if (err) return next(err);
    if (!find) {
      return res.json(utils.createErrorJsonResponse(404, "User not found!"));
    }
    return res.render('home', {
      title: 'Organizator',
      user: find
    });
  })
});

I think is not usefull show you my jade file, the only important thing is that there are lots of imported scripts, but just for give an example, this is how i load a css file:

  link(href='css/style.css', rel='stylesheet')

This is how i setup the static file

  app.use(express.static(config.root + '/public',{ maxAge: 86400000 }));

Where 'config.root' is my is:

path.normalize(__dirname + '/..')

As i said before if i connect to the basic page, so in my case:

http://localhost:3000

all my static files are imported, but as soon as i redirect i got 404. So how can i fix it? For example. I have a style file named 'style.css'. In the basic page ('http://localhost:3000) from the console i can see:

Request URL:http://localhost:3000/css/style.css
Request Method:GET
Status Code:200 OK (from cache)

Then from 'http://localhost:3000/home/':

Request URL:http://localhost:3000/home/css/style.css
Request Method:GET
Status Code:404 Not Found

So the problem is the '/home', but how can i "remove" it from static files request? Thank you.

like image 441
Francesco Z Avatar asked Sep 13 '25 09:09

Francesco Z


1 Answers

As explained well @Molda in comments, make sure your links start with /, otherwise the path will be relative to the actual route http://localhost:3000/home.

like image 87
Jose Hermosilla Rodrigo Avatar answered Sep 15 '25 23:09

Jose Hermosilla Rodrigo