简体   繁体   English

如何在express.js中发送无效路径的自定义消息?

[英]How to send custom messages for invalid paths in express.js?

The below method in express.js express.js中的以下方法

var express = require('express'), app = express();
app.get('/users', function (req, res) {
    //Some logic
}

can be accessed using URL 可以使用URL访问

http://<host-name>:<port>/users

If invalid path such as http://:/invalid-path, I get the following response 如果无效路径(例如http://:/ invalid-path),我将收到以下响应

Cannot GET /invalid-path 无法获取/ invalid-path

Is there a way to send customized messages for invalid paths in express.js? 有没有一种方法可以为express.js中的无效路径发送自定义消息?

One way we can achieve this is with app.all eg 实现这一目标的一种方法是使用app.all例如

app.all('/*,function(req,res){
    var path = req.url;
    switch(path){
    case '/login':
      //logic
    default:
      res.send("Invalid");
    }
})

Yes, you are talking about a 404 not found page if I am not mistaking. 是的,如果我没有记错的话,您是在谈论“ 404未找到”页面。

The way you do this with express, is actually very easy. 使用Express进行此操作的方法实际上非常简单。 Express matches routes in the order they are defined, which means, if you try to access a route that is not defined, it will try all the previous routes, until there are no more. Express按定义的顺序匹配路由,这意味着,如果尝试访问未定义的路由,它将尝试所有先前的路由,直到没有更多路由为止。 So what you need is a route defined to catch any request not already matched. 因此,您需要的是定义为捕获尚未匹配的任何请求的路由。

How? 怎么样?

Easy, as the very last route defined(So no more routes are defined in the code after this route), you define the following route: 很简单,因为定义了最后一条路由(因此在此路由之后的代码中没有定义更多路由),因此您可以定义以下路由:

app.all(function(req, res, next) {
    // Your 404 logic here
}

You can create a middleare error, somelike this.. 您可以创建一个Middleare错误,如下所示。

/middleware/error.js /middleware/error.js

exports.notFound = function(req, res, next) {
  res.status(404);
  res.render('not-found');
};

The not-found can be specific page with message of not found status. 未找到可以是带有未找到状态消息的特定页面。

After your routes you need to catch all the 404 (urls which are not served by any route) and then make some middlewares for error handling depending on the /path: 路由之后,您需要捕获所有404(任何路由都不提供的URL),然后根据/ path制作一些中间件来进行错误处理:

// catch 404 and forward to error handler
app.use(function (req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

// error handlers
app.use('/api', function (err, req, res, next) {
    res.status(err.status || 500);
    res.json({
        message: err.message,
        error: err
    })
});

app.use(function (err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: err
    });
});

I made a custom error handler which shows a custom error page (you can modify the template in /views/error.jade), while for requests starting with /api (/api/something, etc..) I return a json error message. 我制作了一个自定义错误处理程序,其中显示了一个自定义错误页面(您可以在/views/error.jade中修改模板),而对于以/ api开头的请求(/ api / something等),我返回了json错误消息。

This is /views/error.jade: 这是/views/error.jade:

extends layout 扩展布局

block content
  h1= message
  h2= error.status
  pre #{error.stack}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM