JMA
JMA

Reputation: 994

How to serve file with static resources on all routes in Express JS?

How to serve file with static resources on all routes in Express JS?

I tried serving file with static resources using these line of codes,

app.use(Express.static(`${this.PATH}`));
app.use(Cors());
app.use(Express.json()); 
app.get('*', (req, res) => {
    res.sendFile('./index.html',{root: path});
});

If the user visit route 'localhost/test', response is the index.html file. Then main.js is fetched also.

So this first part is working. However, if the user visit route 'localhost/test/testing', response is the index.html file but the main.js is not fetched correctly. The content of main.js is index.html that makes it result to "Uncaught SyntaxError: Unexpected token '<'"

Upvotes: 0

Views: 230

Answers (1)

jfriend00
jfriend00

Reputation: 707218

It seems that the most likely possibility is that you need to change the <script> tag in index.html from this:

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

to this:

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

When you enter /test/testing in the URL bar, the browser will request that file from your server. Your server will send back index.html. Then, the browser will parse that file and see the request from this tag:

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

Since there is no path on the file being requested, the browser will add the path of the current page to that file before it sends the request to the web server. That means, it will send a request for:

/test/testing/main.js

to your web server. But, your express.static() route won't find a file that matches that path. Therefore, it will fall through to your res.sendFile('./index.html',{root: path}); and the browser will get an HTML file when it's expecting a Javascript file and will thus give you the error you report.

I'm personally not a fan of catch all routes like you have that send index.html for anything that doesn't match something else because it can lead to very confusing bugs or problems, but if you do so, you HAVE to not use relative paths with any of your URLs in your page because they will all break when someone requests something like /test/testing.

Upvotes: 0

Related Questions