NodeJS + Express served HTML file not loading js file?
Here's what's happening:
The browser requests
/
, which is responded to by your catchall route, so it gets backindex.html
.The browser then sees a script in the html at
./test.js
, so the browser then interprets that as/test.js
and makes a request for that. Theexpress.static
middleware looks uppublic/test.js
, which does not exist, so it passes execution to the next defined route that matches the request, which is your catchall route. This means html is sent for the javascript file, hence the error that you see.
So to fix this, you need to change ./test.js
to the actual relative path (./app/views/test.js
) or use an absolute path (/app/views/test.js
) to make sure the correct path is always used, no matter what the current path is.
Additionally, you will need to change this:
app.use(express.static('/public'));
to something like this:
app.use(express.static(__dirname + '/public'));
Otherwise the express.static
middleware will look for a directory named public
off the root of your filesystem and you will have the same problem with the catchall route serving html for your javascript file request.
You should set your static folder like this
app.use(express.static(__dirname + '/public'));
Also, your html file will look inside the /public folder itself for your script file. You'll need to give your index.html file the right path to your script file.
<script src="/app/views/test.js"></script>