How to reference a variable in regex URL?

Issue

router.get("/(A|B)/account/", async (req, res) => {});

How to do I reference the (A|B) inside of the async function?

Solution

I guess your route responsibility is getting account information of only A or B. So let’s change your router path to /account/:name(A|B), then your express router will look like this:

router.get("/account/:name(A|B)", async (req, res) => {
    const name = req.params; // A or B
});

Only 2 kinds of requests are handled by this router:

GET /account/A
or
GET /account/B

Answered By – hoangdv

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published