sabbir
sabbir

Reputation: 2025

catch multiple route for single request

In my node.js app, I have one router.get("/*) route for handle all get request, expect dashboard. Which will be handled by router.get("/dashboard"). Now problem is router.get("/*") always called even if request route is router.get("/dashboard"). My code is given below:

 const express = require('express');
 const router = express.Router();

 // route for dashboard
 router.get("/dashboard", (req, res, next) => {
    res.render("index", { title: "dashboard"});
 })

 // this route will handle all get request
 router.get("/*", (req, res, next) => {

   res.render("index", {title: "index"})
})

Here when request is router.get("/dashboard"), both router.get("/*) and router.get("/dashboard") are called. And first router.get("/dashboard") is called and then router.get("/*) is called.

All I want is that just ignore router.get("/*) when request come for router.get("/dashboard").

How can I solve this problem? Thanks in advance.

Upvotes: 0

Views: 194

Answers (3)

Shuhail Alam
Shuhail Alam

Reputation: 174

Your app.get("*") will invoke always. Even if you try to invoke app.get("*"), you'll notice, that the method is invoking twice. That's because, browser is trying to get a fevicon for your site. if you console.log the req.originalUrl, you'll notice that, "/favicon.ico" is the additional call.

To solve this, you can either define a favicon for your site or disable it.

function ignoreFavicon(req, res, next) {
  if (req.originalUrl === "/favicon.ico") {
    res.status(204).json({ nope: true });
  } else {
    next();
  }
}

app.use(ignoreFavicon);

Upvotes: 1

Nikola Jovanovic
Nikola Jovanovic

Reputation: 366

You can use app.get('*', and also you would need to put it after all other endpoints, something like this:

app.get('/dashboard', (req, res) => {
  ...
});

app.get('/foo', (req, res) => {
  ...
});

app.get('*', (req, res) => {
  ...
});

Upvotes: 0

Chaim Friedman
Chaim Friedman

Reputation: 6253

In your catch all route would need to remove the /. It should look like this

router.get("*", (req, res, next) => {

   res.render("index", {title: "index"})
})

Upvotes: 0

Related Questions