CodeHip
CodeHip

Reputation: 377

Node.js route error: script MIME types are not allowed when 'X-Content-Type: nosniff' is given

My css and js files are not found / does not load under second route. They do load fine under first.

Why does this happen ?

  // **********************  INDEX PAGE  *******************************************
    app.get('/LimeLINE', (req, res) => {
        let sTopHtml = fs.readFileSync(__dirname + '/components/top.html', 'utf8')
        let sMainHtml = fs.readFileSync(__dirname + '/html/index.html', 'utf8')
        let sBottomHtml = fs.readFileSync(__dirname + '/components/bottom.html', 'utf8')

        // replace placeholders
        sTopHtml = sTopHtml.replace('{{title}}', 'LimeLINE: Get Started')

        res.send(sTopHtml + sMainHtml + sBottomHtml)
    })

    app.get('/LimeLINE/activate/:token', (req, res) => {
        let sToken = req.params.token;
        if (token === sToken) {
            user.activateUser(res, sToken)
        }
        let sTopHtml = fs.readFileSync(__dirname + '/components/top.html', 'utf8')
        let sMainHtml = fs.readFileSync(__dirname + '/html/index.html', 'utf8')
        let sBottomHtml = fs.readFileSync(__dirname + '/components/bottom.html', 'utf8')
        // replace placeholders
        sTopHtml = sTopHtml.replace('{{title}}', 'LimeLINE: Welcome')
        sMainHtml = sMainHtml.replace('{{click-trigger}}', 'click-trigger')

        res.send(sTopHtml + sMainHtml + sBottomHtml)
    })

Upvotes: 1

Views: 4643

Answers (1)

d_shiv
d_shiv

Reputation: 1790

You should avoid using relative urls in templates which will be served from different routes. In this case same html is getting served from http://<hostname>/LimeLINE as well as http://<hostname>/LimeLINE/activate/:token. The relative url of ../css/main.css will point to different locations in those two cases. Since the browser doesn't know about the directory structure on your server, it simply constructs the path relative to current url (in address bar).

For the first case it becomes http://hostname/../css/main.css which is same as http://hostname/css/main.css;

And in second case it is http://<hostname>/LimeLINE/activate/../css/main.css which is same as http://<hostname>/LimeLINE/css/main.css.

Just change to absolute urls (or relative to host urls, starting with /) and your code will work fine. Instead of href="../css/main.css" use href="/css/main.css"

Upvotes: 2

Related Questions