繁体   English   中英

在Express JS中,如何在Middlware之后呈现静态文件不在公共或查看文件夹中

[英]How to render static file not in public or view folder after middlware in express js

我有一个文件夹

里面的api-docs我有index.html一些CSS和js文件

我需要为经过身份验证的用户呈现api-doc。

我不在视图中使用它,因为在项目中我在视图中使用玉器,而api-doc在html中

我努力了

router.get('/v1/secure-api-documentation',(req,res)=>{
     console.log('A')
     res.sendFile(__dirname + '/../api-doc/index.html');
 });

router.get('/v1/secure-api-documentation',ensureAuthenticate,(req,res)=>{     
     express.static(path.join(__dirname,'../api-doc'))
 });

express.static(path,[options])返回一个函数。 所以基本上您的代码正在做的是:

router.get('/v1/secure-api-documentation',ensureAuthenticate,(req,res)=>{
    express_static_function // this function further accepts arguments req, res, next
    //there is no function call happening here, so this is basically useless
 });

但是,这不是express.static用于express.static的用途,它采用请求路径并在您指定的文件夹中查找具有相同名称的文件。

基本上,如果GET请求到达“ / v1 / secure-api-documentation” ,它将采用“ / v1 / secure-api-documentation”之后的请求路径,并在api_docs文件夹中查找该路径 将express.static传递给router.get()将在非常特殊的路径中调用它。 这个很重要。 GET '/v1/secure-api-documentation/index.html'将失败。 因为这样的路线没有处理。

为此,您需要为任何路径(例如'/ v1 / secure-api-documentation / *' )调用express static。

为此,您需要使用express应用程序对象,并编写以下代码:

//make sure to use the change the second argument of path.join based on the file where your express app object is in.
app.use('/v1/secure-api-documentation',express.static(path.join(__dirname,'../api-doc')));

现在,这不仅适用于index.html文件,而且还适用于api_docs中要求的任何js / css文件。

暂无
暂无

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

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