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

Node/Express特定页面CSS样式表路由异常问题求助

Node/Express页面CSS路由异常:请求路径自动添加/accomplishments前缀导致404

在Node/Express开发中,访问/accomplishments/newAccomplishment页面时,CSS文件请求返回404错误。通过morgan日志可看到,浏览器实际请求路径为/accomplishments/css/utilities.css和/accomplishments/css/style.css,但正确路径应为/css/utilities.css和/css/style.css。页面跳转链接可正常进入目标页,但样式无法加载。

相关代码

路由配置

// @desc    Show new accomplishment page
// @route   GET /accomplishments
router.get("/", ensureAuth, accomplishmentsController.getAccomplishments)
router.get("/newAccomplishment", ensureAuth, accomplishmentsController.getNewAccomplishment)
router.post("/newAccomplishment", ensureAuth, accomplishmentsController.newAccomplishment)

EJS跳转链接代码

<section id="headerInfo">
  <h1 id="topicHeading">Celebrate Your Success With Others</h1>
  <h2> Add an Accomplishment <a href="/accomplishments/newAccomplishment"><i class="fas fa-plus-circle fa-lg"></i></a></h2>
</section>

问题原因

核心问题是EJS模板中CSS资源的引用路径使用了相对路径,而非以/开头的绝对路径。

当页面URL为/accomplishments/newAccomplishment时,浏览器会将相对路径(比如css/style.css)解析为当前URL路径的子路径,也就是/accomplishments/css/style.css,导致请求的资源路径错误,触发404。

而跳转链接使用了绝对路径/accomplishments/newAccomplishment,不受当前页面URL层级影响,因此能正常跳转。

解决方法

  1. 将EJS中所有静态资源(CSS、JS、图片等)的引用路径改为以/开头的绝对路径,例如把css/style.css改为/css/style.css。
  2. 确认Express已正确配置静态资源目录,示例代码如下(假设静态资源存放在项目根目录的public文件夹下):
const path = require('path');
app.use(express.static(path.join(__dirname, 'public')));

内容的提问来源于stack exchange,提问作者aquile hollins

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 14:05:39