Vue-Router与Express结合时出现MIME类型错误求助
Vue-Router + Express 多层路由MIME类型错误解决
问题现象
使用Vue-Router搭配Express部署后,访问二级及以上路由(如/gta/natives)时浏览器出现MIME类型错误,页面仅显示空白Vue模板;本地调试模式一切正常,仅首页和404页面能正常工作。
错误提示:
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.
相关代码
Express 服务端代码
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`));
Vue Router 配置代码
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(), });
问题原因
访问多层路由时,浏览器会以当前路由路径作为基准路径请求静态资源(比如/gta/natives/js/chunk-xxx.js),但实际静态资源存放在根目录下的js文件夹中。由于Express的通配路由/*会在静态资源找不到时返回index.html,导致JS模块请求拿到的是HTML文件,触发MIME类型校验错误。
解决方案
1. 配置Vue项目的静态资源根路径
根据你的构建工具,设置静态资源的公共路径为根路径:
- Vite 项目:在
vite.config.js中添加base: '/'
export default defineConfig({ base: '/', // 其他配置项 })
- Vue CLI 项目:在
vue.config.js中添加publicPath: '/'
module.exports = { publicPath: '/', // 其他配置项 }
2. 确认Express静态资源服务配置无误
确保express.static指向的${__dirname}/html目录包含Vue构建后的所有静态文件(js、css、assets等),且通配路由/*放在静态资源服务之后(当前代码已满足此要求)。
内容的提问来源于stack exchange,提问作者Phill
相关产品推荐
相关产品推荐

