在控制器方法裏面,有沒有辦法訪問靜態文件?我正在使用mailgun發送電子郵件,並且需要發送位於/ public的請求中的html文件。Node/Express - 有沒有辦法從控制器方法訪問靜態文件?
app.post('/', function(req, res) {
var html = getHtml(); // Need to get the html here to pass to mailgun
}
在控制器方法裏面,有沒有辦法訪問靜態文件?我正在使用mailgun發送電子郵件,並且需要發送位於/ public的請求中的html文件。Node/Express - 有沒有辦法從控制器方法訪問靜態文件?
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/'});
});
試試這工作正常