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

Express EJS项目中CSS已正常返回但无法生效的问题求助

Express + EJS项目CSS无法生效问题求助

项目目录结构

ejs_portfolio/
├── public/
│   ├── stylesheets/
│   │   └── style.css
│   ├── images/
│   │   ├── kawsNWF.png
│   │   ├── Potter.png
│   │   └── image1.1.png
│   └── videos/
│       └── Video.mp4
├── views/
│   ├── layout.ejs
│   ├── header.ejs
│   ├── footer.ejs
│   ├── home.ejs
│   ├── aboutMe.ejs
│   ├── contactMe.ejs
│   └── myProjects.ejs
├── routes/
└── app.js

Express静态文件与视图配置

const express = require('express')
const path = require('path');
const app = express();

// Serve static files
app.use(express.static(path.join(__dirname, 'public')));

// View engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

// Routes
const indexRouter = require('./routes/index');
app.use('/', indexRouter);

EJS布局中CSS引入方式

在layout.ejs里引入CSS:

<link rel="stylesheet" type="text/css" href="/stylesheets/style.css">

已完成的排查步骤

  • 直接访问CSS文件:通过http://localhost:3000/stylesheets/style.css可正常获取原始CSS内容
  • 内联样式测试:layout.ejs中<style>标签定义的样式无效,仅HTML元素的行内style属性生效
  • 浏览器网络面板检查:style.css返回200状态码,但样式未应用到页面
  • 清除缓存:尝试清除浏览器缓存并开启「禁用缓存」功能,问题依旧
  • 极简HTML测试:public目录下的test.html文件中,内联<style>标签的样式可正常生效

疑问

  1. 为什么style.css能正常返回内容,却无法在EJS布局中生效?
  2. app.js的配置是否存在遗漏或错误?

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 14:52:13