繁体   English   中英

Express.js 处理未处理的路由

[英]Express.js Handle unmached routes

我开发了一个 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"}))
});

1.声明你所有的路线

2.定义不匹配的路由请求到END错误响应。

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

服务器.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 - 这不是一个有效的路由

您会看到错误消息。

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

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

首先你需要定义所有现有的路由,然后最后你必须定义没有路由。 顺序很重要

 // 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