简体   繁体   中英

Jade/pug setting MIME type of javascript file to text/html

Hey I've been trying to use jade/pug to have my node.js backend render my pages in the front end. I need to include some javascript to make some functionality work but I can't seem to get it to load correctly. I get this error:

"The script from “ http://localhost:3000/public/javascript/newCust.js ” was loaded even though its MIME type (“text/html”) is not a valid JavaScript MIME type.

new Loading failed for the with source “ http://localhost:3000/public/javascript/newCust.js ”."

I have tried setting the content type to javascript and tried moving the directories around to help solve the issue.

script(type='text/javascript' src='public/javascript/newCust.js')

I see you had put your static javascript files in the correct place, ie in a folder named public. But, in order to serve all static files : html, css and javascript files, you need to add a built-in middleware function, namely express.static() , in your entry point which is usually app.js or index.js file, like so :

app.use(express.static('public'));
// you can also use the absolute path, using npm package named path like below :
// app.use(express.static(path.join(__dirname, 'public')));

The express.static() function will combine your static javascript file with that public folder. Therefore, in your pug file, you should write as follow :

script(type='text/javascript' src='./javascript/newCust.js')

not

script(type='text/javascript' src='./public/javascript/newCust.js') 

You don't even need to add the MIME type in that script tag, because by default, the script tag will have the correct MIME type of :

type='text/javascript'

Try with and without adding that MIME type, both should work.

For more detail about using express.static() function, you can read in Express built-in middleware function : express.static()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM