只有缺少路由才能将Express.js设置为404? [英] How can I get Express.js to 404 only on missing routes?

查看:166
本文介绍了只有缺少路由才能将Express.js设置为404?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前我有以下所有其他路线:

At the moment I have the following which sits below all my other routes:

app.get('*', function(req, res){
  console.log('404ing');
  res.render('404');
});

根据日志,即使在上面匹配路由时也会被触发。

And according to the logs, it is being fired even when the route is being matched above. How can I get it to only fire when nothing is matched?

推荐答案

你只需要把它放在所有路线的尽头。

You just need to put it at the end of all route.

看看传递路径控制

var express = require('express')
  , app = express.createServer();

var users = [{ name: 'tj' }];

app.all('/user/:id/:op?', function(req, res, next){
  req.user = users[req.params.id];
  if (req.user) {
    next();
  } else {
    next(new Error('cannot find user ' + req.params.id));
  }
});

app.get('/user/:id', function(req, res){
  res.send('viewing ' + req.user.name);
});

app.get('/user/:id/edit', function(req, res){
  res.send('editing ' + req.user.name);
});

app.put('/user/:id', function(req, res){
  res.send('updating ' + req.user.name);
});

app.get('*', function(req, res){
  res.send('what???', 404);
});

app.listen(3000); 

或者,您可以不做任何事情,因为所有不匹配的路由都会产生一个404.那么可以使用这个代码显示正确的模板:

Alternatively you can do nothing because all route which does not match will produce a 404. Then you can use this code to display the right template:

app.error(function(err, req, res, next){
    if (err instanceof NotFound) {
        res.render('404.jade');
    } else {
        next(err);
    }
});

它记录在错误处理

这篇关于只有缺少路由才能将Express.js设置为404?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆