Search code examples
javascriptnode.jsexpressrouterroot

Express.js main router working, but others routers on him not


I have the problem on routers. My main route /weather working, but others routers on him don't.

app.js

const express = require('express');
const weatherRoute = require('./back/routes/weatherRouter.js');

const app = express();

app.use(bodyParser.json());
app.disable('etag');
app.use('/weather', weatherRoute);

weatherRouter.js

const router = express.Router();

router.get('/', async (req, res) => {
    try {
        const wholeData = await WeatherInfo.find();
        res.json(wholeData);
    } catch (err) {
        res.json({ message: err })
    }
});

router.get('/now', (req, res) => {
  res.send("ITS NOT WORKING");
});

module.exports = router;

the problem is that localhost:5000/weather working perfect, but when I want to use some other routers on that Route e.g. localhost:5000/weather/now that's not working
Any ideas what I'm doing wrong ?

UPDATED :

it works, when between those routers is no others routers.

e.g.

 router.get('/', async (req, res) => {
//working 
    }
    router.post('/:add', async (req, res) => {
//working
    }
    router.get('/now', async (req, res) => {
//doesnt work
    }

If I move /now above /add router it works perfect. Can someone explain why is this happening ?


Solution

  • I found the solution.
    The routers position is matter. Reference to explanation My last router didn't work, because another router already catched him.

    app.get('/:add', function (req, res) {
      // this will match all /a, /b .. including /new
      res.end('done!');
    });
    
    app.get('/now', function (req, res) {
      // this is never called
      res.end('done!!');
    });