Home > OS >  Problem with static routing in Node.js using express
Problem with static routing in Node.js using express

Time:12-23

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

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

CodePudding user response:

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.

CodePudding user response:

You don't need multiple routes to serve your static contents, and the static method of express do such kind of tasks for you:

// If your 'public' or 'static' directory is one of root directories
app.use(express.static(process.cwd()   '/public'));

// so all these requests will be served:
// -> /public/styles/custom.css
// -> /public/scripts/pollyfils.js
// -> /public/media/logo.png
  • Related