2012-03-27 81 views
12

例如在JavaScript防止图像加载错误去JavaScript控制台

var image = new Image(); 
image.onerror = function(e) { 
    // handle error my way 
} 
image.src = "http://bad.location.com/img.jp" 

我已经试过

e.preventDefault() 
return false 

但错误仍然登录到控制台。也许这不是一件坏事,但我正在做的是将文件上传到服务器,然后处理它们并将工件加载到S3。这一切都需要很长时间。我在后台执行此操作,并提前将S3 URL返回给浏览器,并使用一些javascript来使用image.onerror回调来ping图像url以检测图像是否在S3上到达。

这一切正常,但我得到一个控制台错误的负载。这有点难看。有没有什么办法可以隐藏这个 。

回答

0

思来分享一下我刚刚发现。 :)谷歌搜索没有帮助,所以我花了相当一段时间,似乎是值得的!确实是有一个解决方案(如果你控制后台太

例如在的NodeJS:

/* 
* Custom 404 middleware to handle missing image for certain routes 
*/ 

const path = require ('path'); 
const fs = require ('fs-extra'); 

// @root - root folder 
// @exclude - exclude folder 
module.exports = (root, exclude) => (req, res, next) => { 

    if (req.originalUrl.match (exclude)) { 
     fs.stat (path.join (root, req.originalUrl), function (err, stat) { 

      if (err === null) { 

       // if file exist call next = fallback to static handler 
       next(); 

      } else { 

       // if file does not exist, return a fake 200 img response 
       res.writeHead (200, { 
        'Content-Type' : 'image/png', 
        'Content-Length': 0, 
        'Cache-Control' : 'public, max-age=0', 
        'X-Status'  : '404' 
       }); 

       return res.end(); 
      } 
     }); 
    } else { 
     next(); 
    } 

}; 

然后,你可以这样调用它:

let static_path = path.join (__dirname, 'public'); 
app.use (require ('./middleware/missing-image') (static_path, 'img/path')); 
app.use (express.static (static_path)); 

X-状态只是添加了一个自定义头部,以便您可以在客户端JS中检测到响应已被覆盖。

注意:res.end()也可以用来回传回退图像。