Search code examples
node.jstypescriptexpress

Why is this Express Router catchall route overriding a route above it?


I can't figure out why this routing configuration, with eRouter being an express.Router() defined in an index.ts and passed in, is causing the top route of GET /wzdx/DeviceFeed to be overwritten and return a 400 Bad Request. Answers like this one here seem to suggest that the overwrite shouldn't happen.

    constructor(eRouter: ERouter) {

        super()

        const tag = "[" + WZDxDeviceFeed.ClassNamePath + "]"

        const path = "/wzdx/DeviceFeed"

        logger.info(tag, "Initializing HTTP GET Route:", path)

        eRouter.get(path, (eRequest: ERequest, eResponse: EResponse) => {

            this.receive(eRequest, eResponse)

        })

        const catchAllPath = "*"

        eRouter.use(catchAllPath, (_eRequest: ERequest, eResponse: EResponse) => {

            this.respond(eResponse, 400, { error: { code: 400, message: "Bad Request" } })

        })


    }

As soon as the second route is commented out the top route is reachable. What am I doing wrong? Newbie to Typescript and Express. Thank you!


Solution

  • constructor(eRouter: ERouter) {
        super();
    
        const tag = "[" + WZDxDeviceFeed.ClassNamePath + "]";
    
        const path = "/wzdx/DeviceFeed";
    
        logger.info(tag, "Initializing HTTP GET Route:", path);
    
        eRouter.get(path, (eRequest: ERequest, eResponse: EResponse) => {
            this.receive(eRequest, eResponse); // Ensure receive sends a response
        });
    
        // Use a catch-all route handler, not middleware, for unmatched routes
        eRouter.all('*', (_eRequest: ERequest, eResponse: EResponse) => {
            this.respond(eResponse, 404, { error: { code: 404, message: "Not Found" } });
        });
    }