例如在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来ping图像URL,使用image.onerror回调来检测图像是否在S3上到达。
这一切都有效但我收到了很多控制台错误。这有点难看。有什么办法吗? 隐藏这个。
答案 0 :(得分:8)
很抱歉,似乎无法取消该错误,至少在Google Chrome中是这样。
另请参阅:Check if file exists but prevent 404 error in console from showing up
答案 1 :(得分: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-Status只是添加了一个自定义标头,因此您可以在客户端JS中检测到响应已被覆盖。
注意:res.end()也可用于流回一个后备图像。