Cody Cody - 1 year ago 27
Node.js Question

In express link to static assets breaks when user visits a 404 page

I am using express to create a simple application. I have coded my templates using handlebars which looks like something this:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" lang="english">
<title>{{ title }} </title>
</head>
<body>

{{{body}}}

<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script src="js/my.js"></script>
</body>
</html>


The problem is that if a user visits a 404 page, then link to every static assets in the site breaks. The only solution I have found is to hardcode links to static files like this:

<script src="http://localhost:3000/js/my.js"></script>


Obviously, This is not the recommended way. How you guys tackle this issue ?
I have coming from Django background, and it really provides a consistent and easy way to link static contents. Do we have something similar in express (or handlebars).

Thanks

Answer Source

Change this line

<script src="js/my.js"></script>

to

<script src="/js/my.js"></script>

Currently, you are looking for the my.js file within the same folder as the current page (relative path).

For example, if your page exists at: http://localhost:3000/myroute/mypage

It will look for the javascript file at http://localhost:3000/myroute/js/my.js

By changing it to /js/my.js it will point to the root of the site (absolute path): http://localhost:3000/js/my.js

HTML Filepaths

All About File Paths

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download