A very simple question but bothers me a lot.
what's the difference between the following two cases ?
index.html
- script src="script/a.js"
- script src="/script/a.js" // starting with slash
and why my server can serve this request (starts with slash)
app.get('/script/a.js', function(req, res){ // with slash
res.sendfile(__dirname + '/realfolder/script/a.js');
});
no matter the url src on client side is any case of those two cases I just mentioned ?
On the other hand, I always got 404 error if I serve the request in the following way (starts without slash)
app.get('script/a.js', function(req, res){ // without slash
res.sendfile(__dirname + '/realfolder/script/a.js');
});
In my opinion, the path starts from '/' means the root folder of application and the other means relative path from __dirname. And I couldn't understand why my server can't handle app.get('script/a.js') this request which is without slash in the beginning ?
Anything wrong ?
When a path starts with a slash / it means that it is an absolute path.
When it doesn't start with a slash, it is a relative path.
Lets see an example. Imagine that my hard disk has only the following folders:
main
subfolder1
subfolder2
lastfolder
Now imagine we are in folder subfolder2 and we want to load a file that is inside lastfolder. We can load it with a relative path:
lastfolder/file.txt
But we can also use an absolute path:
/main/subfolder2/lastfolder/file.txt
Both paths are correct, but the relative one can fail if we move to a different folder (for example if we are in subfolder1), while the absolute path will always be correct (if we don't modify the folders of course).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With