I have setup a webserver using NodeJS, which returns the file index.html. Howevern when i try to import a JavaScript file to my html file, my browser gives the error
The resource "http://localhost:3000/includes/main.js" was blocked because of a MIME-Type-Conflict ("text/html")
I do see what the problem is, but i don’t know how to fix it.
My NodeJS code:
var express = require('express');
const app = express();
app.use(express.static('includes'));
app.use(express.static('views'));
app.set('views', 'views');
app.set('view engine', 'pug');
app.get('/', async (req, res) => {
res.render('index');
})
app.listen(3000, () => {
console.log('listening on port 3000');
})
My Project folder structure:
/
app.js
/views
index.html
/includes
main.js
2
Answers
This is not a NodeJs issue but an Express setup thingy, which you are using to setup a server.
Serving static files in Express: https://expressjs.com/en/5x/api.html#express.static
read also about
res.render()
which renders viewshttps://expressjs.com/en/5x/api.html#res.render
setup your apps views folder where you keep all html views
https://expressjs.com/en/5x/api.html#app.set
If you decide to use a templating engine other than plain html you’d need to add the following line (this is not necessary if you’re just working with plain HTML files – which is the case here):
Modify Your index.html file and include the javascript file in your index.html file as below it works fine.
The line you have in your app.js file
This is used to lookup the static files like images,js,css so Whatever you defined inside that folder you can use that by including them.
As in index.html file you can include main.js file in script tag. like this:
Use the same server.js file as you given.
Use the CodeSandBox where I have implemented this check at https://codesandbox.io/p/devbox/expresscheck-3g9p5k