简体   繁体   中英

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.

EDIT :

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 (eg 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.

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