Javier Guzmán
Javier Guzmán

Reputation: 1163

Why my javascript file is not found in the public folder?

I was trying to make my first web and I had the following route in my node.js code:

app.get("/contact_form", function(req, res){
    res.render("new_contact");
});

new_contact was including correctly my javascript file and I was doing that with:

<script type="text/javascript" src="scripts/jquery.min.js"></script>

Now I have changed my route to:

app.get("/contact_form/new", function(req, res){
    res.render("new_contact");
});

And it stopped working; I had to change the including with a / before scripts to make it work again:

<script type="text/javascript" src="/scripts/jquery.min.js"></script>

Please, could someone explain me thoroughly what it is going on? I have taken a look to several answers and websites but all explanations are very vague kind of: 1. The slash means the root. 2. Without the slash is a relative path

And so son.

Thank you in advance.

Upvotes: 0

Views: 1149

Answers (1)

Davin Tryon
Davin Tryon

Reputation: 67296

If you have the url: https://localhost/contact_form, then a relative path (src="scripts/jquery.min.js") will look for the jquery using:

https://localhost/scripts/jquery.min.js

Once you made the change, you had this url: https://localhost/contact_form/new. If you continue to use the relative path, the browser will look for jquery using:

https://localhost/contact_form/scripts/jquery.min.js

Which wouldn't work, because it isn't there. It is at the root.

So changing to the root path (src="/scripts/jquery.min.js") will always start from the root path (just after the domain):

https://localhost/scripts/jquery.min.js

Upvotes: 2

Related Questions