思来分享一下我刚刚发现。 :)谷歌搜索没有帮助,所以我花了相当一段时间,似乎是值得的!确实是有一个解决方案(如果你控制后台太)
例如在的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()也可以用来回传回退图像。
来源
2017-11-07 18:40:45
ShQ