Home > database >  How to append parameter to GET request
How to append parameter to GET request

Time:12-15

I'm kinda new to backend so I'm not sure how to append my parameter to my GET request which is then sent to the my server. Let's say I have 4 projects, each with {projectID: 1, projectID: 2...} and when I click on the first project with projectID: 1 I will send a GET request to localhost:3000/api/launch/projects/1. But I have no idea how to write the route in my backend to get the 1 as parameter.
Here's the code:

route.get(
    "/projects/",    // how to receive the projectID as parameter
    async (req: Request, res: Response, next: NextFunction) => {
    // ... some code
    const data = await launchServiceInstance.getProjectsByID(projectsID);  // projectID has to be 1
    }
  );

CodePudding user response:

I am not quite sure if I understood well, but I'll try to answer. First, you should add 'id' to the route. Second, you can access the id with 'req.params.id'. So the code would be:

route.get(
    "/projects/:id",    // how to receive the projectID as parameter
    async (req: Request, res: Response, next: NextFunction) => {
    // ... some code
    const data = await launchServiceInstance.getProjectsByID(req.params.id);  // projectID has to be 1
    }
  );

CodePudding user response:

If this is server code you can access parameters (for GET request):

route.get(
    "/projects/:projectsID", // add here to parameter
    async (req: Request, res: Response, next: NextFunction) => {
       const { projectsID } = request.params; // access parameter
       const data = await launchServiceInstance.getProjectsByID(projectsID);
    }
);
  • Related