简体   繁体   English

Express.js 处理未处理的路由

[英]Express.js Handle unmached routes

Fellows I develop a Rest API and I want when a route does not exist to send a custom message instead of an html one that express.js sends by default.我开发了一个 Rest API,我希望当路由不存在时发送自定义消息而不是 express.js 默认发送的 html 消息。 As fas as I searched I could not find a way to do that.正如我搜索的那样,我找不到办法做到这一点。

I tried to do:我试图做:

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

But it matches and all already implemented methods.但它与所有已经实现的方法相匹配。 I want only the unmached one to get handled by my app.我只希望我的应用程序处理未加工的那个。

Edit 1编辑 1

For each enndpoint I create a seperate file having the following content: eg.对于每个端点,我创建了一个具有以下内容的单独文件:例如。 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)
   })
}

An in my main file I use:我在主文件中使用了一个:

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"}))
});

1.Declare all of your routes 1.声明你所有的路线

2.Define unmatched route request to error respose AT the END . 2.定义不匹配的路由请求到END错误响应。

This you have to set it in the app.这你必须在应用程序中设置它。 (app.use) not in the routes. (app.use) 不在路线中。

Server.js服务器.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);

Please note : I have prefix '/api' in my routes.请注意:我的路由中有前缀“/api”。

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

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

When you try http://localhost:8081/api4545 - which is not a valid route当你尝试http://localhost:8081/api4545 - 这不是一个有效的路由

You would see the error message.您会看到错误消息。

Can't post as comment (reputation is too low ...) but did you define this route after all your other paths ?不能发表评论(声誉太低......)但是你是否在所有其他路径之后定义了这条路线?

The order is really important, you should first define all your routes and then have this one.顺序真的很重要,你应该首先定义你的所有路由,然后有这个。

First you need to define all existing routes then at last you have to define no route.首先你需要定义所有现有的路由,然后最后你必须定义没有路由。 order is very important顺序很重要

 // 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();
 });

就我的路线生命周期的安全性而言,我使用了这个**/***/** (星号)运算符代表所有,这是我的例子。

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

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

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