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