2

I'm having a small problem here. I want to display 404 not found if I input a wrong route.

The code below only shows 404 not found if I go to http://localhost:3000/

but when I enter http://localhost:3000/wrongroute it displays Cannot GET /wrongroute instead of 404 not found.

const bodyParser = require("body-parser");
const mysql = require('mysql');
const router = express.Router();

const db = mysql.createConnection({
    host: 'xxx.xx.xx.xx',
    user: 'root',
    password: '12345',
    database: 'test'
});

db.connect((err) =>{
    if(err){
        throw err;
    }
    console.log('Mysql Connected');
    // res.send("Mysql Connected");
});

router.post('/login', function (req, res) {
      res.send("This is from login route");
   res.end();
})

router.post('/signup', function (req, res) {
   res.send("This is from signup route");
   res.end();
})

router.get('/', function(req, res){
 res.send("404 not found");
});


module.exports = router;
guntbert
  • 536
  • 6
  • 19
Pakz
  • 123
  • 2
  • 15
  • Does this answer your question? [How to redirect 404 errors to a page in ExpressJS?](https://stackoverflow.com/questions/6528876/how-to-redirect-404-errors-to-a-page-in-expressjs) – Xaqron Apr 22 '20 at 07:16

2 Answers2

2

Add this route at the END.

router.get("*", (_, res) => res.status(404).send("404 not found"))
Darvesh
  • 645
  • 7
  • 15
1

Here's your solution. Remember to place the fallback route at the end of your endpoint list.

router.post('/your-route', function (req, res) {
   ...
});

router.post('/another-route', function (req, res) {
   ...
});

router.get('*', function(req, res) {
  // This is a fallback, in case of no matching

  res.status(404);
  res.send('Not found.');
});