Skip to content Skip to sidebar Skip to footer

Express.js Handle Unmached Routes

Fellows I develop a Rest API and I want when a route does not exist to send a custom message instead of an html one that express.js sends by default. As fas as I searched I could n

Solution 1:

1.Declare all of your routes

2.Define unmatched route request to error respose AT the END.

This you have to set it in the app. (app.use) not in the routes.

Server.js

//Import require modulesvar express = require('express');
var bodyParser = require('body-parser');

// define our app using expressvar app = express();

// this will help us to read POST data.
app.use(bodyParser.urlencoded({ extended: true }));

app.use(bodyParser.json());

var port = process.env.PORT || 8081;    

// instance of express Routervar router = express.Router(); 

// default route to make sure , it works.
router.get('/', function(req, res) {
    res.json({ message: 'hooray! welcome to our api!' });   
});

// test route to make sure , it works.
router.get('/test', function(req, res) {
    res.json({ message: 'Testing!' });   
});


// all our routes will be prefixed with /api
app.use('/api', router);

// this is default in case of unmatched routes
app.use(function(req, res) {
// Invalid request
      res.json({
        error: {
          'name':'Error',
          'status':404,
          'message':'Invalid Request',
          'statusCode':404,
          'stack':'http://localhost:8081/'
        },
         message: 'Testing!'
      });
});

// state the server
app.listen(port);

console.log('Server listening on port ' + port);

Please note : I have prefix '/api' in my routes.

Please try http://localhost:8081/api

You will see '{"message":"hooray! welcome to our api!"}'

When you try http://localhost:8081/api4545 - which is not a valid route

You would see the error message.

Solution 2:

First you need to define all existing routes then at last you have to define no route. order is very important

// Defining main template navigations(sample routes)

 app.use('/',express.static(__dirname + "/views/index.html"));
 app.use('/app',express.static(__dirname + "/views/app.html"));
 app.use('/api',express.static(__dirname + "/views/api.html"));
 app.use('/uploads',express.static(path.join(__dirname, 'static/uploads')));

 //If no route is matched by now, it must be a 404

 app.use(function(req, res, next) {
  res.status(404);
  res.json({status:404,title:"Not Found",msg:"Route not found"});
  next();
 });

Solution 3:

Can't post as comment (reputation is too low ...) but did you define this route after all your other paths ?

The order is really important, you should first define all your routes and then have this one.

Solution 4:

on my case for the safetyness of my routes life cycle I used this **/** or */*, *(asterisk) operator stands for all, and here's my example.

app.use('**/**',express.static(path.join(__dirname, './public/not-found/index.html')));

Post a Comment for "Express.js Handle Unmached Routes"