首页 > 解决方案 > Javascript / Node.js 导入 html 文件

问题描述

我正在制作一个 node.js 服务器,它可以按需发送电子邮件。变量“输出”是我想通过电子邮件发送的。当我使用内联 html 时,它可以正常工作,但是我想导入一个完整的 html 文件。

我尝试使用 <object> 和 <link> 导入与 app.js 位于同一文件夹中的“file.html”,但两者都显示为白页。

app.post("/send", (req, res) => {
    console.log("sending email...");
    const email = req.body.data.email;
    const customerId = req.body.data.customer_id;
    const orderId = req.body.data.order_id;

    //const output = `<h3>Hi, this works</h3>` // WORKS
    //const output = `<object type="text/html" data="file.html"></object>`; // Doesn't work
    const output = `<link href="file.html" rel="import" />`;                    // Doesn't work
;

非常感谢您的帮助。如有必要,我可以提供更多代码。

标签: javascriptnode.jsnodemailer

解决方案


将其插入到您的 .post 方法之外,以便在您的程序启动并填充输出时运行一次,而不是在每次调用 .post 或 .get 方法时读取文件

const fs = require('fs');
const output = fs.readFileSync('/path/to/file.html').toString();

推荐阅读