Node / Express - 有没有办法从控制器方法访问静态文件?

Node / Express - Is there a way to access static files from a controller method?

在控制器方法中,有没有办法访问静态文件?我正在使用 mailgun 发送电子邮件,需要在我的请求中发送位于 /public.

的 html 文件
app.post('/', function(req, res) {
    var html = getHtml(); // Need to get the html here to pass to mailgun
}

有没有办法使用 Express 提供的一些方便的设备访问静态文件目录?不,我不知道。

有什么方法可以完成您想要做的事情吗?当然。使用 fs 模块阅读它。我也喜欢使用 path 模块来生成我的文件路径。

const path = require("path");
const fs   = require("fs");

// Do however you like to build paths. 
// I like to use resolve so I always get an absolute path.
const publicPath = path.resolve(__dirname, "public"); 

const htmlPath = path.join(publicPath, "thefile.html");

app.post('/', function (req, res, next) {
  fs.readFile(htmlPath, "utf8", onFile);

  function onFile (err, html) {
    if (err) return next(err); // assuming you're using an error handler, like you probably should be
    mailgunThatStuff(html, mgDone);  
  }

  function mgDone (err) {
     if (err) return next(err);
     res.end("OK mailgun'd that thing");
  }
}

这可能有点罗嗦。有道理吗?

你可以试试这个

(app.js) 你刚刚在 app.js

中提到了静态文件夹
var express = require('express');
var app = express();
app.use(express.static('public'));

index.html页面在本地花./public/pages/

app.all('/', function (req, res) {
    res.sendFile('index.html', {root: './public/pages/'});
});

尝试一下它工作正常