繁体   English   中英

如何在 express JS 中提供动态 static 文件

[英]How to serve dynamic static files in express JS

我正在尝试渲染 static 文件。 我遇到了 sendFile() 方法,但它不适用于代理。 我需要帮助。 这是我的代码。

var express = require('express');
const proxy = require('express-http-proxy');
var process = require('process');

var app = express();
app.set('port', (process.env.PORT || 8080));

app.use('$Variable',  express.static(__dirname + '$Variable'));
app.use('/', proxy(function(request, response) {
  return 'http://localhost:8000' + request.url
}))

process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
app.listen(app.get('port'));
setTimeout(function() {
  process.exit();
}, 100000);

我想要这样的东西有人知道吗? 我该怎么做才能将 $variable 替换为我的文件的路径。 注意: $VARIABLE 只是为了展示我想要表达的意思。 这并不意味着我试图在 node.js 中使用 PHP。 在你成为教授之前三思而后行。

要将 URL 和 append "/webapp" 的路径放到它的末尾,然后在文件系统中查找与要服务的文件匹配的文件,您可以这样做:

const path = require('path');

app.get((req, res, next) => {
    const file = path.join(__dirname, req.path, "webapp");
    res.sendFile(file, { dotfiles: "deny" }, (err) => {
        if (err) {
            console.log(err);
            // decide what you want to do here with an error
            // either call next(err), call next() to continue routing
            // or send a 404 response
            res.sendStatus(404);
        }
    });
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM