【问题标题】:Prevent image load errors going to the javascript console防止图像加载错误进入 javascript 控制台
【发布时间】:2012-04-11 05:47:06
【问题描述】:

例如在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。

一切正常,但我收到大量控制台错误。这有点难看。有没有什么办法 隐藏这个。

【问题讨论】:

    标签: javascript image


    【解决方案1】:

    抱歉,似乎无法抑制该错误,至少在 Google Chrome 中是这样。

    另请参阅:Check if file exists but prevent 404 error in console from showing up

    【讨论】:

      【解决方案2】:

      想分享我刚刚发现的东西。 :) 谷歌搜索没有帮助,所以我花了很长时间,似乎值得!确实有一种解决方案(如果你也控制后端

      例如在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-Status 只是添加的自定义标头,因此您可以在客户端 JS 中检测到响应已被覆盖。

      注意:res.end() 也可用于流回后备图像。

      【讨论】:

        猜你喜欢
        • 2017-06-16
        • 2015-10-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-03-12
        • 2013-02-23
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多