[英]How to include CSS files in Express.js views when not using a template engine?
I'm trying to create an Express application.我正在尝试创建一个 Express 应用程序。 My limitations are that I cannot use any template engine for rendering HTML.
我的限制是我不能使用任何模板引擎来呈现 HTML。 There are (at least) two problems:
有(至少)两个问题:
For problem 2. I've tried:对于问题2。我试过:
app.get('/transactions', (req, res) => res.sendFile(path.join(__dirname+'/public/assets/html/transactions.html')))
and then in transactions.html I have然后在 transactions.html 我有
<link rel="stylesheet" href="../stylesheets/shared/constants.css">and other links to stylesheets.
When the page is displayed, it doesn't apply any of the styles.当页面显示时,它不应用任何样式。 When I checked the source code in the browser, and I click the link for constants.css it shows the message:
当我在浏览器中检查源代码并单击 constants.css 的链接时,它会显示消息:
Cannot GET /stylesheets/shared/constants.css无法获取 /stylesheets/shared/constants.css
This doesn't seem like the right logic.这似乎不是正确的逻辑。 What things should be changed?
应该改变什么?
Simple example:简单示例:
Assuming your folder structure:假设您的文件夹结构:
app.js
| +-- public
| | +-- stylesheets
| | | +-- shared
| | | | +-- constants.css
...
You could simply server public folder as static like:您可以简单地将公用文件夹作为静态服务器,例如:
app.use(express.static(__dirname + "/public"))
// In your html
<link rel="stylesheet" href="/stylesheets/shared/constants.css">
With express, it's better to use absolute
path over relative
path.对于 express,最好使用
absolute
路径而不是relative
路径。
Or set up virtual path for your static files like:或者为您的静态文件设置虚拟路径,例如:
app.use('/static', express.static(__dirname + "/public"))
// In your html
<link rel="stylesheet" href="/static/stylesheets/shared/constants.css">
Simple Example worked for me:简单的例子对我有用:
app.use(express.static(__dirname + "/publlic"))
app.get('/', (req, res) => {
app.engine('html', cons.swig);
app.set('view engine', 'html');
res.render('index');
})
// In your html
<link rel="stylesheet" href="/static/stylesheets/shared/constants.css">
With this method, I use engine like you.通过这种方法,我像你一样使用引擎。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.