【问题标题】:Express.js Handle unmached routesExpress.js 处理未处理的路由
【发布时间】:2017-11-16 06:39:39
【问题描述】:

伙计们,我开发了一个 Rest API,我希望在不存在路由时发送自定义消息,而不是 express.js 默认发送的 html 消息。就我搜索的速度而言,我找不到这样做的方法。

我尝试过:

  app.all("*",function(req,res){
     res.status(404)
     res.header("Content Type","application/json")
     res.end(JSON.stringify({message:"Route not found"}))
  });

但它匹配并且所有已经实现的方法。我希望我的应用只处理未加工的。

编辑 1

对于每个端点,我创建一个具有以下内容的单独文件:例如。 myendpoint.js

module.exports=function(express){

   var endpoint="/endpoint"

   express.get(endpoint,function(req,res){
      res.end("Getting data other message")
   }).post(endpoint.function(req,res){
      res.end("Getting data other message")
   }).all(endpoint,function(req,res){
      res.status(501)
      res.end("You cannot "+res.method+" to "+endpoint)
   })
}

我使用的主文件中的一个:

var endpoint=require('myendpoint.js')
var MyEndpointController=endpoint(app)
app.all("*",function(req,res){
   res.status(404)
   res.header("Content Type","application/json")
   res.end(JSON.stringify({message:"Route not found"}))
});

【问题讨论】:

  • 确保您的 app.all('*' ... 路线是您定义的最后一条路线,因为 Express 将按照您定义它们的顺序匹配所有路径。因此,如果这条路线要成为第一个,它将匹配每个请求。将其保留到最后将首先尝试匹配之前的每个路由,然后默认为 *.
  • stackoverflow.com/questions/44537806/… 访问上方并帮助我解决此问题

标签: javascript node.js rest express


【解决方案1】:

1.声明你所有的路线

2.将不匹配的路由请求定义为错误响应AT the END

您必须在应用程序中设置它。 (app.use) 不在路线中。

Server.js

//Import require modules
var express = require('express');
var bodyParser = require('body-parser');

// define our app using express
var app = express();

// this will help us to read POST data.
app.use(bodyParser.urlencoded({ extended: true }));

app.use(bodyParser.json());

var port = process.env.PORT || 8081;    

// instance of express Router
var router = express.Router(); 

// default route to make sure , it works.
router.get('/', function(req, res) {
    res.json({ message: 'hooray! welcome to our api!' });   
});

// test route to make sure , it works.
router.get('/test', function(req, res) {
    res.json({ message: 'Testing!' });   
});


// all our routes will be prefixed with /api
app.use('/api', router);

// this is default in case of unmatched routes
app.use(function(req, res) {
// Invalid request
      res.json({
        error: {
          'name':'Error',
          'status':404,
          'message':'Invalid Request',
          'statusCode':404,
          'stack':'http://localhost:8081/'
        },
         message: 'Testing!'
      });
});

// state the server
app.listen(port);

console.log('Server listening on port ' + port);

请注意:我的路线中有前缀“/api”。

请尝试http://localhost:8081/api

你会看到'{"message":"hooray! Welcome to our api!"}'

当您尝试http://localhost:8081/api4545 - 这不是有效路线

您会看到错误消息。

【讨论】:

    【解决方案2】:

    首先你需要定义所有现有的路线然后你必须定义 no 路线。顺序很重要

     // Defining main template navigations(sample routes)
    
     app.use('/',express.static(__dirname + "/views/index.html"));
     app.use('/app',express.static(__dirname + "/views/app.html"));
     app.use('/api',express.static(__dirname + "/views/api.html"));
     app.use('/uploads',express.static(path.join(__dirname, 'static/uploads')));
    
     //If no route is matched by now, it must be a 404
    
     app.use(function(req, res, next) {
      res.status(404);
      res.json({status:404,title:"Not Found",msg:"Route not found"});
      next();
     });
    

    【讨论】:

      【解决方案3】:

      无法发表评论(声誉太低......),但您是否在所有其他路径之后定义了这条路线?

      顺序真的很重要,你应该先定义你所有的路线,然后有这个。

      【讨论】:

        【解决方案4】:

        为了我的路线生命周期的安全性,我使用了 **/***/**(asterisk) 运算符代表所有,这是我的示例。

        app.use('**/**',express.static(path.join(__dirname, './public/not-found/index.html')));
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2019-09-17
          • 2018-10-05
          • 1970-01-01
          • 2013-02-27
          • 1970-01-01
          • 2018-01-29
          • 2016-06-11
          相关资源
          最近更新 更多