Home > Back-end >  Handling different URL paths while hitting a single endpoint (Nodejs)
Handling different URL paths while hitting a single endpoint (Nodejs)

Time:04-26

I am using express nodejs to hit an endpoint:

app.use("/number", numberRouter);

Now I have to handle URL in which the path is different. Here we have three different paths in the same URL:

  • https://localhost:8080/number/one
  • https://localhost:8080/number/two
  • https://localhost:8080/number/three

The file in which the numberRouter is handled:

numberRouter.post("/", async (req:Request, res:Response) => {
    var url = req.protocol   '://'   req.get('host')   req.originalUrl;

    //what I want to do
    if (req.path == "one") {
        //do something
    } 
    else if (req.path == "two") {
       //do something
    }
});

What I want to achieve is that once I hit the number endpoint, I fetch the full URL, extract out it's path and based on the path I do further processing instead of hitting three different endpoints (/number/one, /number/two, /number/three). Is this possible?

I am using postman for testing and if I send a post request with the following URL: localhost:8080/number/one the post request fails. I want something like this in the code:

numberRouter.post("/variablePath", async (req:Request, res:Response) => { ... }

where the variablePath is set via postman (one, two or three) and then processed here.

SOLUTION (following @traynor's answer):

app.use("/number", numberRouter);
numberRouter.post("/:pathNum", async (req:Request, res:Response) => {
    if (req.path === "/one") {
        //do something
    } 
    else if (req.path === "/two") {
       //do something
    }
});

The post request via postman: localhost:8080/number/:pathNum. In postman set the value of pathNum in the Params section under the Path Variables heading.

enter image description here

CodePudding user response:

use route parameters

add your parameter to the router, for example /:myparam, and then check it and run your code:

numberRouter.post("/:myparam", async (req:Request, res:Response) => {
    const myParam = req.params.myparam;

    //what I want to do
    if (myParam == "one") {
        //do something
    } 
    else if (myParam == "two") {
       //do something
    }

});
  • Related