You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js+Express加载Bootstrap失败:MIME类型错误及404问题求助

解决Express加载Start Bootstrap Bare模板时CSS/JS无法加载的问题

问题原因

你的报错本质是Express找不到静态资源文件(CSS/JS):当请求这些文件时,Express返回了HTML格式的404页面,导致浏览器解析时出现MIME类型不匹配错误;部分资源直接报404,说明文件路径映射完全错误。

解决方案

先确认你的项目文件结构,再对应修改代码:

场景1:模板文件直接放在项目根目录

如果你的项目结构是这样:

项目根目录/
├── index.js
├── index.html
├── css/
│   └── styles.css
└── js/
    └── scripts.js

修改index.js中的静态服务配置,让Express服务当前目录下的所有静态文件:

import express from 'express';
import path from 'path';
import { fileURLToPath } from 'url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

const app = express();
const port = 4000;

// 修改为服务当前目录的静态文件
app.use(express.static(__dirname));

app.get('/', (req, res) => {
    res.sendFile(path.join(__dirname, 'index.html'));
});

app.listen(port, () => {
    console.log(`Example app listening on port ${port}`);
});

同时确保index.html中的资源引用是相对路径(模板默认就是相对路径,无需修改):

<link href="css/styles.css" rel="stylesheet">
<script src="js/scripts.js"></script>

场景2:模板文件放在public目录下

如果你想把静态资源统一放在public目录,结构如下:

项目根目录/
├── index.js
└── public/
    ├── index.html
    ├── css/
    │   └── styles.css
    └── js/
        └── scripts.js

修改index.js,让Express服务public目录的静态文件,并且可以删除单独的根路由(因为express.static会自动返回public下的index.html):

import express from 'express';
import path from 'path';
import { fileURLToPath } from 'url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

const app = express();
const port = 4000;

// 服务public目录下的静态文件
app.use(express.static(path.join(__dirname, 'public')));

// 无需手动处理根路由,express.static会自动返回public/index.html
// app.get('/', (req, res) => {
//     res.sendFile(path.join(__dirname, 'index.html'));
// });

app.listen(port, () => {
    console.log(`Example app listening on port ${port}`);
});

关键说明

  • 当express.static指定的目录和实际静态文件位置不匹配时,Express无法找到资源,会返回HTML格式的404页面,这就是浏览器报MIME类型错误的核心原因。
  • 确保HTML中的资源引用路径和express.static映射的路径一致:如果静态服务指向public,那么css/styles.css会对应public/css/styles.css;如果指向根目录,则对应根目录下的css/styles.css。

内容的提问来源于stack exchange,提问作者Fadhil Mulyono

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 16:27:36