Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Problem with static routing in Node.js using express

I am having an issue with some custom routing code, it all works fine and is in sync with the client-side view routing I do, but as soon as I have a subpage, it doesn’t route my static files correctly.

Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "text/html". Strict MIME type checking is enforced for module scripts per HTML spec.

Rather than giving me a file from the root directory, it’ll serve it as if it were from the subfolder.

Example: i go to http://localhost/sign-up, and files loading in my index file from /scripts are loaded, but if i go to http://localhost/sign-up/2, it’ll attempt to load the script from /sign-up/scripts

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const express = require('express');
const path = require('path');

const app = express();

app.use('/views', express.static(path.resolve(__dirname, 'frontend', 'views')));

app.use('/styles', express.static(path.resolve(__dirname, 'frontend', 'styles')));
app.use('/scripts', express.static(path.resolve(__dirname, 'frontend', 'scripts')));
app.use('/media', express.static(path.resolve(__dirname, 'frontend', 'media')));

app.get('/*', (req, res) => {
    res.sendFile(path.resolve(__dirname, 'frontend', 'newSite.html'));
});

app.listen(process.env.PORT || 1234, () => console.log('Server is now running...'));

To manage this I have been following these tutorials by DCODE on youtube, but I can’t see anything amiss:

https://www.youtube.com/watch?v=6BozpmSjk-Y

https://youtu.be/OstALBk-jTc

>Solution :

Resources loaded in the sign up folder should use URLs beginning with a ‘/‘ character, to make them relative to the site root, e.g.

src="/scripts/modulefile.js"
href="/css/stylesheet.css"
href="/media/image.png"

and not urls relative to the signup folder – which they will be if the leading '/' is omitted.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading