想分享我刚刚发现的东西。 :) 谷歌搜索没有帮助,所以我花了很长时间,似乎值得!确实有一种解决方案(如果你也控制后端)
例如在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() 也可用于流回后备图像。