0

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.

Mahfuz
  • 9
  • 1
  • 6

2 Answers2

2

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)
S. Sandeep
  • 237
  • 3
  • 11
1

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();});
Daphoque
  • 4,421
  • 1
  • 20
  • 31
  • same result. when the request comes to route "/a" then it found in ''/*". both are executed – Mahfuz Sep 14 '18 at 03:13
  • cuz your /a handler, here require("./controllers/handler1.js"); has to stop the flow with : res.status(200).json({key: "value"}); or res.send("erter"); if you don't stop the flow, it pass through the other "matching" middleware until the end. – Daphoque Sep 14 '18 at 11:29