Hristo Marinov
Hristo Marinov

Reputation: 11

Not able to load static files in Pug althrough the static file directory has been set in Express.js

I am building an application and I am trying to send an email that uses Pug as a template engine and I am having problems loading static files in my template. My code successfully sets the public folder of my project as the static one and I am able to access the content of the files in the browser.

However, the files are not loaded in my Pug template when I use a relative path with respect to the public directory. I also tried specifying their absolute path which actually works.

The directory structure of my application is:

app

+/public

  +/css

    style.css

  image.png

+/src

  +/client

  +/server

    +/templates

      +/verify

        html.pug

        text.pug

    +server.js

server.js

require('dotenv').config({path: __dirname + "/../../.env"});
const path = require('path');

const express = require('express');
const app = express();
const port = 8080;

const cors = require('cors');
const bodyParser = require('body-parser');

app.use(cors());
app.use(bodyParser.urlencoded({extended: true }));
app.use(bodyParser.json());

app.set('view engine', 'pug');
app.use(express.static(path.join(__dirname, '../../', 'public')));

const nodemailer = require('nodemailer');
const Email = require('email-templates');

const transporter = nodemailer.createTransport({
  address: 'smtp.gmail.com',
  host: 'smtp.gmail.com',
  port: 465,
  secure: true,
  service: 'gmail',
  auth: {
    user: process.env.SENDER_EMAIL,
    pass: process.env.SENDER_PASS
  },
  authentication: 'plain',
  enable_stattls_auto: true
});

const email = new Email({
  transport: transporter,
  views: {
    root: './templates'
  },
  send: true,
  preview: false
});

email.send({
  template: 'verify',
  message:  {
    from: process.env.SENDER_EMAIL,
    to: '*email*',
    subject: 'Activise - Email Verification',
  },
  locals: {}
})
.then(() => console.log('EMAIL SENT'))
.catch(err => console.log("ERROR: " + err));

app.listen(port, () => console.log('Server listening for requests on port 8080!'))

Here is my Pug code as well

html.pug

doctype html
html
    head
        title=title
        link(rel="stylesheet", href="/css/style.css" type="text/css")
    body
        .email-text
            img(src="/image.png", alt="Application logo")

Upvotes: 1

Views: 1959

Answers (2)

Prosenjit Barman
Prosenjit Barman

Reputation: 81

Make sure that the path of the Public folder you have mentioned on the express.static middleware is correct. It is currently pointed to two directories back from the current server.js file.

Upvotes: 0

Jared Barrett
Jared Barrett

Reputation: 83

in the server.js

change

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

to

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

also change you pug to this

link(rel='stylesheet', href='/css/style.css')

Upvotes: 1

Related Questions