0

I'm trying to create an Express application. My limitations are that I cannot use any template engine for rendering 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. E.g. I have a transactions table in my database and I need to display an HTML table of all those transactions. 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.
  2. I'm sending an HTML file when I call a specific route, but it cannot get the CSS files from another folder.

For problem 2. I've tried:

 app.get('/transactions', (req, res) =>
    res.sendFile(path.join(__dirname+'/public/assets/html/transactions.html')))

and then in transactions.html I have

<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:

Cannot GET /stylesheets/shared/constants.css

This doesn't seem like the right logic. What things should be changed?

1

2 Answers 2

2

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.

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">
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.