Everytime I want to access a specific route in Express I get the followwing error in my browser while also having a default and blank Vue HTML without content. Everything works in Vue debug mode but after building everything, only the Home page and the 404 page works.
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.
In Express I have the following code:
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
this.app.use(express.static(`${__dirname}/html`));
this.app.get('/*', (req, res) => res.sendFile(`${__dirname}/html/index.html`));
In my router.ts in vue I have the following code:
import { defineAsyncComponent } from "vue";
import { createRouter, createWebHistory } from "vue-router";
import Natives from '../views/Natives.vue';
const router = createRouter({
routes: [
{
path: "/",
name: "Home",
component: defineAsyncComponent(() => import('../views/Home.vue')),
meta: {
name: "Home",
},
},
{
path: "/gta",
name: "GTA V",
component: defineAsyncComponent(() => import("../views/GTA.vue")),
meta: {
name: "GTA"
}
},
{
path: "/gta/natives",
name: "Natives",
component: Natives,
meta: {
name: "GTANatives",
},
},
{
path: '/gta/natives/:hash',
name: 'Native',
component: defineAsyncComponent(() => import("../views/DetailedNative.vue")),
meta: {
name: "DetailedNative"
}
},
{
path: "/:pathMatch(.*)*",
name: "Page not found!",
component: defineAsyncComponent(() => import("../views/NotFound.vue")),
meta: {
name: "NotFound",
},
},
],
history: createWebHistory(),
});
I appreciate any help.
EDIT: So I found out when this happens. So basically if there are more than two routes for example /gta/native or simply /a/b this error appears even if the page doesn't exist. But I still can't figure out how and why.
CodePudding user response:
It seems mime
module does not have a type mapping for vue
ext.
You can check from https://github.com/broofa/mime/tree/main/types
https://expressjs.com/en/4x/api.html#express.static
Since express.static
middleware support setHeaders
option, you can set the header by self.
const express = require('express')
const app = new express();
app.use(express.static(__dirname '/public', {
setHeaders: (res, path, stat) => {
if (/\.vue/i.test(path))
res.setHeader('Content-Type', 'application/javascript')
}
}))
app.listen(55555, '0.0.0.0', () => {
const http = require('http');
http.get('http://127.0.0.1:55555/test.vue', res => console.log(res.headers['content-type']))
});
Test output
$ node app
application/javascript
CodePudding user response:
So I found the answer somehow. Everything was caused because I had a "corrupted" vite.config.ts
. After removing base: './'
, everything worked flawlessly.