Search code examples
javascriptnode.jsexpresshandlebars.jsexpress-handlebars

How to force Express JS to serve files from the same directory regardless of route?


I am writing an express app that uses a template engine called Handlebars. The html files it serves contain images that point to certain places in my root directory. This works fine for surface-level routes such as "http://localhost:5000/image" or "http://localhost:5000/login". However, when I go to a deeper route such as "http://localhost:5000/image/1", all of the images point to a nonexistent "/image" folder in my root directory. Screenshots demonstrating this here: The first image uses a surface-level route, /image

The second image uses a deeper route, /image/1

How can I force my pages to only point to my root directory regardless of which route the user is in? I cannot simply change the src in the html files as I am using a template engine that serves the same banner image regardless of what page the user is on.

Here is my codeenter image description here


Solution

  • You're approaching this from the direction.

    Currently you are using relative paths in your HTML. <img src="assets/etc…

    These are resolved by taking the base URL (usually the path to the current HTML document), removing the fragment id, query string, and everything after the last / and then appending the relative path.

    So the resolved path will change based on the URL of the HTML document you are viewing.


    You could do what you are asking for and write code so that:

    /assets/foo
    /something/assets/foo
    /something-else/assets/foo
    /something/something/assets/foo
    

    All give you the same resource.

    However:

    • This would break caching of that resource
    • It would be a pain to write
    • You might get duplicate content penalties in search engines

    So don't do that.


    Instead, pick a URL for the resource and change the HTML so you are always asking for the same URL.

    Use an absolute path which starts with a /.

    These are resolved in a similar way to relative URLs, but instead of stripping off everything after the last / they strip off everything after the hostname (and optional port number).

    <img src="/assets/etc…