代码之家  ›  专栏  ›  技术社区  ›  astavrou

将受保护的图像从API显示到下一个。img标签中的js客户端

  •  1
  • astavrou  · 技术社区  · 4 年前

    我正在尝试从我的节点显示受保护的图像。js后端资产文件夹。

    它有一个中间件,用于检查用户是否已登录并有权访问该文件。

    在客户端,我想在img标签中显示图像:

    <img src“localhost:5000/uploads/image.png”/>

    是否有办法拦截该请求以传递用户的令牌,以便他能够访问该图像?

    谢谢

    2 回复  |  直到 4 年前
        1
  •  1
  •   Bubun    4 年前

    您可以通过以下方式之一实现这一点:

    1. 使用Cookies进行身份验证
    2. 使用令牌作为图像URL的查询参数

    曲奇饼

    登录时,您可以向浏览器发送cookie,并使用中间件验证用户是否具有查看图像的权限。

    router.use("/uploads", function(req, res, next) {
        // Check if the user is loged in
        if (req.isAuthenticated()) {
        next();
        } else {
            res.status(401).send("You are not authorized to view this page");
        }
    });
    
    // Static files
    router.use("/uploads", express.static(path.join(__dirname, 'public')));
    

    代币

    类似地,您可以使用这样的令牌

    <img src="localhost:5000/uploads/image.png?token=xxxxxxxxxxxxxx" />

    router.use("/uploads", function(req, res, next) {
        // Check if the user is loged in
        if (req.query.token && checkToken(req.query.token)) {
            next();
        } else {
            res.status(401).send("You are not authorized to view this page");
        }
    });
    
    // Static files
    router.use("/uploads", express.static(path.join(__dirname, 'public')));
    

    注意:这段代码以express为例。你必须在你使用的任何库中实现这个中间件。

        2
  •  1
  •   Santosh Karanam    4 年前

    使用blob,您可以延迟将从后端API下载的图像绑定到<img>标签

    <img id="image"/>
    

    来自API的响应被传递给下面的函数

    function response(e) {
       var urlCreator = window.URL || window.webkitURL;
       var imageUrl = urlCreator.createObjectURL(this.response);
       document.querySelector("#image").src = imageUrl;
    }