Мысль поделиться тем, что я только что обнаружил. Гуглить вокруг не помогло, так что я потратил довольно много времени и, похоже, оно того стоит! Действительно, есть одно решение (, если вы тоже управляете бэкэндом )
Например, в 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 () также может использоваться для возврата к резервному изображению.