我开发了一个 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) 不在 route 。
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);
<小时/>
请注意:我的 route 有前缀“/api”。
您将看到 '{"message":"万岁!欢迎使用我们的 api!"}'
当你尝试http://localhost:8081/api4545时- 这不是有效的路线
您会看到错误消息。
关于javascript - Express.js 处理不匹配的路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44539210/