简体   繁体   English

不使用模板引擎时如何在 Express.js 视图中包含 CSS 文件?

[英]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:有(至少)两个问题:

  1. One of the problems that I foresee is how will I manage to manipulate the data based on what I need to show to the user.我预见到的问题之一是我将如何根据需要向用户显示的内容来管理数据。 Eg I have a transactions table in my database and I need to display an HTML table of all those transactions.例如,我的数据库中有一个交易表,我需要显示所有这些交易的 HTML 表。 The traditional way that I'm used is to utilize a template engine, where I can put a for loop that goes through the records.我使用的传统方法是利用模板引擎,我可以在其中放置遍历记录的 for 循环。
  2. I'm sending an HTML file when I call a specific route, but it cannot get the CSS files from another folder.我在调用特定路由时发送了一个 HTML 文件,但它无法从另一个文件夹中获取 CSS 文件。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM