ExpressJS在尝试提供缺失图像时破裂

时间:2018-03-06 22:17:04

标签: node.js express

ExpressJS新手警告

我有一个使用expressjs运行的简单服务器,当所有图像都存在时,一切运行良好。但是如果图像丢失,则表达式会因以下错误而停止

(node:5793) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: Cannot find module 'jpg'

这可以防止加载任何其他内容,甚至链接工作。该页面就在那里。难道不是简单的不提供图像(发送404)并仍然允许网站工作吗?

更新

router.get('/*', (req, res, next) => {
    dynamicStatic.setPath(path.resolve(__dirname, 'public/templates/' + 
    app.get('templatePath')));
    res.render('index');
});

我使用dynamicStatic,因为我需要能够根据某些条件动态设置路径。这在引擎盖下设置了express.static。我不认为这与它有任何关系,因为其他图像正在得到很好的服务。当然,我可能错了。

更新2 图像保持在(挂起)状态,这是挂起的来源。

enter image description here

此图显示我在Node / Express中收到的错误消息。 enter image description here

1 个答案:

答案 0 :(得分:1)

我认为使用try {} catch块捕获异常应该可以正常工作。

将可能在try块中引发异常的代码放入,如果抛出异常,则发送404状态。

这是一个尝试:

router.get('/*', (req, res, next) => {
   try {
         dynamicStatic.setPath(path.resolve(__dirname, 'public/templates/' + 
         app.get('templatePath')));
         res.render('index');
     } catch(err) {
         res.sendStatus(404);
      }
});
相关问题