node.js - 无法通过 Express.js 中设置的静态文件目录在 Pug 中加载静态文件
问题描述
我正在构建一个应用程序,我正在尝试发送一封使用 Pug 作为模板引擎的电子邮件,但在我的模板中加载静态文件时遇到问题。我的代码成功地将我的项目的公用文件夹设置为静态文件夹,并且我能够访问浏览器中文件的内容。
但是,当我使用相对于公共目录的相对路径时,文件不会加载到我的 Pug 模板中。我还尝试指定实际有效的绝对路径。
我的应用程序的目录结构是:
app
+/public
+/css
style.css
image.png
+/src
+/client
+/server
+/templates
+/verify
html.pug
text.pug
+server.js
服务器.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')
推荐阅读
- spring-integration - 手动注册spring集成流和多个子流
- python - 如何迭代到熊猫数据框列并删除特定行?
- matlab - 我可以删除占位符变量以在 Matlab 中节省内存吗?
- jquery - 单击按钮后重新关注输入
- mysql - 使用 REGEXP 在 MySQL 5 中返回特定的捕获组/子字符串
- ruby-on-rails - 具有多个不同ID的表单,如何保存
- excel - 制作列表重置子例程不删除总计行或其包含的公式
- windows - 如何在命令提示符下安装 PolyML
- url-rewriting - IIS 7 URL 重写规则帮助
- artificial-intelligence - 转置表如何与 Hypermax 一起使用?