Having trouble adding a CSS file to my Node.js project with the EJS Template Engine. The file cannot be found when trying to access it.
GET http://localhost/css/bulma.css net::ERR_ABORTED 404 (Not Found)
Project folder structure
./index.js
./views
/partials
/header.ejs
./public
/css
/bulma.css
I have included app.use(express.static)
as follows
app.use(express.static(__dirname + '/public'));
In my header.ejs
file, I include the CSS file like this:
<link href="/css/bulma.css" rel="stylesheet" type="text/css">
Despite trying various solutions, it still doesn't work.
The following approach also does not work:
app.use('public', function(req, res, next){
console.log(req.url); // Never output
next();
});
I have also attempted:
app.use('/public', express.static('public'));
Is anyone able to provide insight into what might be causing the issue?
EDIT
Full server code (index.js)
const express = require('express')
const app = express()
const port = 3000
app.use(express.static(__dirname + '/public'));
// set the view engine to ejs
app.set('view engine', 'ejs');
// index page
app.get('/', function(req, res) {
res.render('pages/index', {
template: '../pages/home'
});
});
app.listen(port, (err) => {
if (err) {
return console.log('something bad happened', err)
}
console.log(`server is listening on ${port}`)
})
index.ejs for dynamic template system
<header>
<%- include('../partials/header') -%>
</header>
<%- include(template) -%>
<footer>
<%- include('../partials/footer') -%>
</footer>
/etc/nginx/sites-available/default
server {
listen 80 default_server;
listen [::]:80 default_server;
root /home/nodejsproject/;
server_name _;
location / {
proxy_pass http://localhost:3000;
# First attempt to serve request as file, then
# as directory, then fall back to displaying a 404.
try_files $uri $uri/ =404;
}
}
Additionally,
console.log(__dirname + '/public');
confirms the correct path to the Node.js project directory
SOLUTION: The issue here was with the NGINX configuration.
After consulting the following resource:
I made adjustments to the config file as shown below:
upstream backend {
server localhost:3000;
}
server {
listen 80;
server_name nodeproject;
root /home/nodeproject/;
location / {
try_files $uri @backend;
}
location @backend {
proxy_pass http://backend;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
# Following is necessary for Websocket support
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
}