繁体   English   中英

如何在express中为静态文件设置动态路由

[英]How to set dynamic route for static files in express

目前,为了提供静态文件,我正在做这样的事情:

app.use('/', express.static(__dirname + '/public/'));
// then i start the server
http.createServer(app).listen(port, function() {
    console.log('HTTP Express server listening on port %s', port);
});

但是,这会在所有条件下为每个请求为该路径设置相同的目录。 我想要做的是这样的事情,改变请求的响应请求:

http.createServer(app).listen(port, function() {
    if (someCondition) {
        app.use('/', express.static(__dirname + '/public/'));
    }
    else {
        app.use('/', express.static(__dirname + '/public/someotherpath'));    
    }
    console.log('HTTP Express server listening on port %s', port);
});

我怎样才能做到这一点?

你以相反的方式修改 url 以达到你想要的效果

app.use('/', function(req,res,next){
    if(condition){
        req.url = newURL // add something to lead to different directory
    }
    next();
});

app.use('/', express.static(__dirname + '/public/'));
// then i start the server
http.createServer(app).listen(port, function() {
    console.log('HTTP Express server listening on port %s', port);
});

老问题......但这是一个快速的解决方案......

如果您想保留express.static附带的所有功能,那么您可以只对req.url猴子补丁(因为它只是中间件):

const path = require('path');
const express = require('express');
const app = express();

// Dynamic path, but only match asset at specific segment.
app.use('/website/:foo/:bar/:asset', (req, res, next) => {
  req.url = req.params.asset;
  express.static(__dirname + '/static')(req, res, next);
});         

// Just the asset.
app.use('/website/*', (req, res, next) => {
  req.url = path.basename(req.originalUrl);
  express.static(__dirname + '/static')(req, res, next);
});

express.static() 的结果是一个中间件函数,因此您可以根据您的条件动态调用它。

app.get('/', (req, res, next) => {
    if (condition) {
        express.static(__dirname + '/public/')(req, res, next);
    } else {
        express.static(__dirname + '/public/someotherpath')(req, res, next);
    }
});

根据您的最后评论:您仍然可以在路由器内执行此操作

app.get('/somepath', function(req, res){
    if(req.someCondition){
      res.sendFile('./path/to/appropriate/file.html');
    } else {
      res.sendFile('./path/to/different/file.html');
    }
}

保留express.static以提供您的常用文件,如 js、css 和图像。 使用.sendFile()方法发送不同的 html 文件。 如果您不想使用诸如 jade 或 ejs 之类的东西,这可以避免必须使用渲染器

我也遇到了同样的问题,现在我通过创建一个条件来解决它,就像下面的代码一样

app.use("/", (req, res, next) => {
  //check a condition if its false then return
  if(1 !== 1)return
  //After returned all conditions
  next()
}, express.static("public"))

并且此代码检查 1 是否不是 1,如果 1 是 1,则不会显示文件,然后它会显示所有公共文件:)

暂无
暂无

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

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