Reputation: 19
I used this code at the bottom of app.js
app.use(function (req, res) {
res.send('Route Not Found');
})
But it executes in every request. I want to execute it only when route is not found.
Upvotes: 0
Views: 1205
Reputation: 257
This works fine. Make sure to place app.get('*' ...
at the end of each file with routes if you are including external routes files.
const express = require('express')
const app = express()
app.get('/', function(req, res){
res.status(200).send('GET /')
})
app.get('/a', function(req, res){
res.status(200).send('GET /a')
})
app.get('*', function(req, res){
res.status(404).send('404')
})
app.listen(3000)
Upvotes: 2
Reputation: 4678
Put your routes handler before :
app.get("/a", require("./controllers/handler1.js"); // catch get route on a
app.get("/b", require("./controllers/handler2.js"); // catch get route on b
app.post("/a", require("./controllers/handler1.js"); // catch post route on a
// error handler, if no route has been caught
app.get("/*", function(req, res){ res.send("404 not found"); res.end();});
app.post("/*", function(req, res){ res.send("404 not found"); res.end();});
Upvotes: 1