Expressjs multiple optional parameters trigger request handler twice

Hello I need a second pair of eyes because I’m not sure why this is happening…
I want to create 1 request handler which might accept 0 or 1 or 2 parameters eg: http://hocalhost:3000/{seed}/{size}, seed and size parameters must be optional.

However the below example doesn’t work and the console.log is being printed twice. This doesn’t happen if I change the handlers route to /api/:seed?/:size?. Why is this happening & what am I doing wrong?

const sharp = require('sharp');
const express = require('express');
const settings = require('./settings');

const app = express();

const calculateDensity = (s) => {

    return (72 * s) / 180;

}

app.get('/:seed?/:size?', (req, res) => {
        
    console.log('Why am I seeing this log?');

    res.end();

})

app.listen(settings.PORT, () => {
    console.log(`Example app listening at http://localhost:${settings.PORT}`)
})

1 thought on “Expressjs multiple optional parameters trigger request handler twice”

  1. So this is your default route

    app.get('/:seed?/:size?', (req, res) => {
            
        console.log('Why am I seeing this log?');
    
        res.end();
    
    })
    

    Lets have another route

    app.get('/test', (req, res) => {
            
        console.log('Test called');
    
        res.end();
    
    })
    

    Now on browser localhost:port/test
    Now which route will call.
    As per your code it will consider that you are calling default route, where your first two argument is optioal.

    So always default route will called. and test route skipped. Because test is now parameter of default route. Not another route

    Think deeply Either test route work or default route

    Reply

Leave a Comment