Express.js处理未路由 [英] Express.js Handle unmached routes
问题描述
研究员,我开发了Rest API,我想在不存在路由时发送自定义消息,而不是默认情况下express.js发送的html消息.正如我搜寻时所发现的那样,我找不到解决办法.
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. As fas as I searched I could not find a way to do that.
我试图做:
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.
对于每个集合点,我创建一个单独的文件,其内容如下: myendpoint.js
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)
})
}
在我使用的主文件中:
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.将不匹配的路由请求定义为错误地重新放置在结束处.
2.Define unmatched route request to error respose AT the END.
您必须在应用程序中进行设置.(应用程序使用)不在路由中.
This you have to set it in the app. (app.use) not in the routes.
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".
Please note : I have prefix '/api' in my routes.
您将看到'{"message":万岁!欢迎使用我们的api!"}'
You will see '{"message":"hooray! welcome to our api!"}'
当您尝试 http://localhost:8081/api4545 -这不是有效路由
When you try http://localhost:8081/api4545 - which is not a valid route
您将看到错误消息.
这篇关于Express.js处理未路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!