Nodejs express routing : no styling if "/" is added

I have no idea how to phrase it(that's why google couldn't help me...) so let me give you an example.

If I go to my page mypage.whatever/login, everything is fine.

But if I go to mypage.whatever/login/, the page has no styling. It only has HTML.

In my main node/express file I have app.use("/login", login);

In the login.js file I have :

router.get("/", function(req,res){ res.render("login", {title: "Login page"}); });

How could I correct this behaviour?

Thanks in advance.


Thanks to Manasov Daniel and jfriend00, I found out where the problem came from.

The stylesheet aren't included when I add a "/" because the routes get messed up.

For instance with a stylesheet like this

<link rel="stylesheet" href="stylesheets/login.css">

Instead of looking for something/stylesheets/login.css

The browser searches for something/login/stylesheets/login.css

Do you guys have an idea how to fix it?


When your style sheets are included with a path like this:

<link rel="stylesheet" href="stylesheets/login.css">

Then, the browser treats them as relative paths and they are evaluated relative to the path of the current page. That is rarely what you want for shared resources so you should probably change to use a leading slash like this:

<link rel="stylesheet" href="/stylesheets/login.css">

The reason it works differently when you do or don't have a trailing slash is because when there is no trailing slash, then /login is treated as the filename and / is the path. So, stylesheets/login.css would be combined with / and the result would be /stylesheets/login.css and it would work.

But, if you use /login/, then that is treated as the path and that path gets combined with your style sheet link to give you /login/stylesheets/login.css which does not work.

The answer is to always include a root path in your stylesheet links (e.g. something that starts with /). Then, they will not be combined with the path of the page, only with the domain and port of the page.

In your main node/express file, you have:

app.use('/login', require('./your_file_path/login')); // login.js file path

And in the login.js file, you should have:

router.get("/login", function(req,res){
    res.render("login", {title: "Login page"});

To answer the edit part :

adding a pre-slash to my css routes fixed the problem.

ie from href="something/myfile.css" to href="/something/myfile.css"

I don't really understand why though.

Need Your Help

SQL meta joins plus Haversine formular

mysql haversine

I have a query which joins a few meta datas to a user.

Mean-Shift sklearn K function

scikit-learn mean-shift

I was trying to read the documentation on sklearn's MeanShift and saw this formula: