Node Express区分来自404文件请求的404页面请求

时间:2017-03-11 18:08:50

标签: node.js express error-handling

我遇到一个问题,例如,我的404渲染会捕获错误的文件请求,css或图像。我真的想要返回404响应,但在这种情况下不会呈现404页面。在过去,我使用nginx处理文件请求,所以这不是问题。但是当express处理文件服务时,正确的方法是什么?

这是我当前的路由处理,后跟错误处理逻辑 -

app.use(express.static(path.join(rootPath, 'public')));
app.use('/', routes);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  // respond with html page
  if (req.accepts('html')) {
    res.render('404', { url: req.url });
    return;
  }

  // respond with json
  if (req.accepts('json')) {
    res.send({ error: 'Not found' });
    return;
  }

  // default to plain-text. send()
  res.type('txt').send('Not found');
  next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message + " " + req.path,
      error: err
    });
  });
}

1 个答案:

答案 0 :(得分:0)

您可以使用Express服务静态中间件:https://expressjs.com/en/resources/middleware/serve-static.html

相关问题