研究員我開發了一個Rest API,我希望在路由不存在的情況下發送自定義消息,而不是默認發送express.js的html消息。就像我搜索的那樣,我找不到一種方法來做到這一點。Express.js處理未擴展的路由
我試圖做的:
app.all("*",function(req,res){
res.status(404)
res.header("Content Type","application/json")
res.end(JSON.stringify({message:"Route not found"}))
});
但是它匹配所有已實現的方法。我只想要未被修改的一個被我的應用程序處理。
編輯1
對於我創建具有下列內容的單獨的文件中的每個enndpoint:例如。 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將按照您定義的順序匹配所有路徑,因此,如果此路線是第一條路線將匹配每一個請求,將它保留到最後將首先嚐試匹配每個以前的路由,然後再默認爲* –
https://stackoverflow.com/questions/44537806/nodejs-shows-error-cannot-get-test/訪問以上並幫助我解決此問題 –