我有个文件夹
api-docs中,我有一些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'))
});发布于 2019-03-28 07:48:53
Express.static(路径,选项)返回一个函数。因此,基本上您的代码所做的是:
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 documentation’,它将在‘/v1/secure documentation’之后选择请求路径,并在api_docs文件夹中查找。将express.static传递给router.get()将为非常特定的路径调用它。这事很重要。GET‘/v1/secure documentation/index.html’将失败。因为这样的路线不会被处理。
您需要做的是对‘/v1/secure documentation/*’这样的任何路径调用express。
为此,您需要使用express app对象,并编写以下代码:
//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文件。
https://stackoverflow.com/questions/55392231
复制相似问题