我有一个文件夹
我里面有index.html一些CSS和JS文件的api-docs
我需要为经过身份验证的用户呈现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'))
});
答案 0 :(得分:2)
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'<<的请求路径/ em>并在 api_docs 文件夹中查找。 将express.static传递给router.get()将在非常特殊的路径中调用它。这个很重要。 GET '/ v1 / secure-api-documentation / index.html'将失败。因为没有处理这样的路线。
您需要执行的操作是对'/ v1 / secure-api-documentation / *'之类的任何路径调用静态表达。
为此,您需要使用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文件。