node.js 使用 Express 在动态路由上提供静态文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11569181/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 16:03:00  来源:igfitidea点击:

Serve Static Files on a Dynamic Route using Express

node.jsexpress

提问by Waylon Flinn

I want to serve static files as is commonly done with express.static(static_path)but on a dynamic route as is commonly done with

我想像通常那样提供静态文件,express.static(static_path)但像通常那样在动态路由上提供

app.get('/my/dynamic/:route', function(req, res){
    // serve stuff here
});

A solution is hinted at in this commentby one of the developers but it isn't immediately clear to me what he means.

一位开发人员在此评论中暗示了一个解决方案,但我并不清楚他的意思。

回答by Waylon Flinn

Okay. I found an example in the source code for Express' response object. This is a slightly modified version of that example.

好的。我在 Express' response object的源代码中找到了一个示例。这是该示例的略微修改版本。

app.get('/user/:uid/files/*', function(req, res){
    var uid = req.params.uid,
        path = req.params[0] ? req.params[0] : 'index.html';
    res.sendFile(path, {root: './public'});
});

It uses the res.sendFilemethod.

它使用该res.sendFile方法。

NOTE: security changes to sendFilerequire the use of the rootoption.

注意:安全更改sendFile需要使用该root选项。

回答by Jeff Tian

I use below code to serve the same static files requested by different urls:

我使用下面的代码来提供不同 url 请求的相同静态文件:

server.use(express.static(__dirname + '/client/www'));
server.use('/en', express.static(__dirname + '/client/www'));
server.use('/zh', express.static(__dirname + '/client/www'));

Although this is not your case, it may help others who got here.

虽然这不是你的情况,但它可能会帮助到这里的其他人。

回答by prograhammer

You can use res.sendfileor you could still utilize express.static:

您可以使用res.sendfile或仍然可以使用express.static

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; // <-- programmatically update url yourself
  express.static(__dirname + '/static')(req, res, next);
});         

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

回答by fvlinden

This should work:

这应该有效:

app.use('/my/dynamic/:route', express.static('/static'));
app.get('/my/dynamic/:route', function(req, res){
    // serve stuff here
});

Documentation states that dynamic routes with app.use()works. See https://expressjs.com/en/guide/routing.html

文档说明动态路由app.use()有效。见https://expressjs.com/en/guide/routing.html