【发布时间】: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