如何仅在丢失的路由上将 Express.js 设置为 404? [英] How can I get Express.js to 404 only on missing routes?

查看:31
本文介绍了如何仅在丢失的路由上将 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.

看一下传递路由控制的第二个例子:>

Take a look at the second example of Passing Route Control:

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天全站免登陆