我正在构建一个应用程序,我正在尝试发送一个使用Pug作为模板引擎的电子邮件,我在模板中加载静态文件时遇到问题。我的代码成功地将项目的公共文件夹设置为静态文件夹,并且我能够访问浏览器中文件的内容。
但是,当我使用相对于公共目录的相对路径时,文件不会加载到我的Pug模板中。我也尝试指定它们实际有效的绝对路径。
我的应用程序的目录结构是:
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!'))
这是我的Pug代码
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")
在server.js中
更改
app.use(express.static(path.join(__dirname, '../../', 'public')));
至
app.use(express.static(path.join(__dirname, 'public')));
也改变你的哈巴狗
link(rel='stylesheet', href='/css/style.css')