简体   繁体   English

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

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

I have a folder 我有一个文件夹

api-docs inside that I have index.html some css and js file 里面的api-docs我有index.html一些CSS和js文件

I need to render api-doc for authenticated user. 我需要为经过身份验证的用户呈现api-doc。

I am not using it in views as In project I am using jade in view and api-doc is in html 我不在视图中使用它,因为在项目中我在视图中使用玉器,而api-doc在html中

I have tried 我努力了

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

and

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

express.static(path, [options]) returns a function. express.static(path,[options])返回一个函数。 So basically what your code is doing is : 所以基本上您的代码正在做的是:

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
 });

However, this is not what express.static is used for What express.static does is, takes the request path and looks for a file with the same name in the folder you specified. 但是,这不是express.static用于express.static的用途,它采用请求路径并在您指定的文件夹中查找具有相同名称的文件。

Basically, if a GET request comes to '/v1/secure-api-documentation' , it will take the request path after '/v1/secure-api-documentation' and look for that inside api_docs folder. 基本上,如果GET请求到达“ / v1 / secure-api-documentation” ,它将采用“ / v1 / secure-api-documentation”之后的请求路径,并在api_docs文件夹中查找该路径 Passing express.static to router.get() will call it for the very SPECIFIC path. 将express.static传递给router.get()将在非常特殊的路径中调用它。 This is important. 这个很重要。 GET '/v1/secure-api-documentation/index.html' will fail. GET '/v1/secure-api-documentation/index.html'将失败。 Because such a route is not handled. 因为这样的路线没有处理。

What you need to do this is call express static for any path like '/v1/secure-api-documentation/*' . 为此,您需要为任何路径(例如'/ v1 / secure-api-documentation / *' )调用express static。

For this you need to take the express app object, and write the following code: 为此,您需要使用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')));

This will now work for not only the index.html file but any js/css file inside api_docs that is requested. 现在,这不仅适用于index.html文件,而且还适用于api_docs中要求的任何js / css文件。

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

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