如何正确提供与Node.js的私人静态文件?

我想保护上传的图像。 当用户上传图片时,他们被保存到以下path:

public/dogs/{userId}/{imageName} 

每个用户都有自己的保存图像的目录。 我已经想通了,如果我做这样的事情,我可以很容易地提供这些图像,但每个人都可以访问这些图像:

 app.use(express.static('public')); 

我的用户validation工作方式,我检查path中请求的url包含/api/admin 。 例:

 router.get('/api/admin/dogs', dog.getAll); 

我想以类似的方式提供图片,以便让pipe理员访问它们。 有没有可能有这样的事情:

 router.get('/api/admin/dogs/images/:userId/:imageName', image.getOne); 

感谢您的帮助。

response对象上有一个sendFile函数。 你可以使用它来发送基于你的用户validation的文件。

这将是这样的:

 router.get('/api/admin/dogs/images/:userId/:imageName', function(req, res, next){ currentUserHasAccessTo(userId, imageName, function(err) { if (err) next(err) else res.sendFile(`public/dogs/${userId}/${imageName}`) }) }); 

currentUserHasAccessTo是您的validationfunction,将查询数据库或其他东西。 如果返回错误,它将被传递给error handling程序中间件,以便它可以显示默认图像或错误页面。

你也可以使用堆栈的处理程序:

 router.get('/api/admin/dogs/images/:userId/:imageName', function(req, res, next){ currentUserHasAccessTo(userId, imageName, function(err) { if (err) next(err); // or res.send(401) if unauthorized else res.next() ; // this will "jump" to the express.static below }) , express.static('public') }); 

在这种情况下,您有一个单一路由的两个处理程序。 第二个将只有在next()被调用时才能达到…