簡體   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