Home > Software engineering >  Having multiple get routes on a NodeJS / Express REST API?
Having multiple get routes on a NodeJS / Express REST API?

Time:11-10

I'm creating a JS web app using NodeJS and Express (with SQL/MySQL for the database), pretty much directly implementing this API tutorial: https://www.bezkoder.com/node-js-rest-api-express-mysql/ (just replacing 'tutorials' with 'Employees').

I'm trying to write API functions to get all Employees with certain attributes (in the SQL table), for example all employees with lastName = "Garcia" or all employees with teamID = 43682, etc.

In my routes.js file I have this:

module.exports = app => {
  const employees = require("../controllers/employee.controller.js");

  const router = require("express").Router();

  // Create a new Employee
  router.post("/", employees.create);

  // Retrieve all Employees
  router.get("/", employees.findAll);

  // Retrieve all Employees with lastName
  router.get('/', employees.findLastName);


... a bunch more CRUD functions ...


  app.use('/api/employees', router);
};

And this is the corresponding Controller function:

exports.findLastName = (req, res) => {
  const lastName = req.query.lastName;   // tried changing req.query.lastName to req.params.lastName

  Employee.getLastName(lastName, (err, data) => {
    if (err)
      res.status(500).send({
        message:
            err.message || "Error occurred while retrieving by last name."
      });
    else {
      console.log(`Employees with lastName ${lastName} were found!` );
      res.send(data);
    }
  });
};

exports.findAll = (req, res) => {
  const title = req.query.title;

  Employee.getAll(title, (err, data) => {
    if (err)
      res.status(500).send({
        message:
          err.message || "Some error occurred while retrieving employees."
      });
    else {
      console.log(`Employee with ${title} title was found!` );
      res.send(data);
    }
  });
};

The findAll route/function (just copied from that tutorial) works by finding all Employees with a certain ID number (the primary key in the DB) and I know that works from testing it through Postman. I wrote the findLastName route/function by copying the findAll function and changing it to search by lastName, and making the corresponding functions in the model and controller classes.

The new function, findLastName, doesn't work... unless I put the route before the findAll route (or comment it out). Then it correctly calls all my functions and returns all employees with the lastName param.

What's actually happening here? Are you not allowed to have multiple .get() routes or something? If so, how would I implement a search API like this? This is my first time building a web app like this so admittedly I'm still a little hazy on how routing and all that works. Thank you for any help though!

CodePudding user response:

In Express whenever the first route matches second will be ignored, so in your scenario you have two route.get with same path /

router.get('/', employees.findAll);

//Since route with path `/` is matched above already this will be ignored 
router.get('/', properties.findLastName);

In order to find Employees with last name you will need to create a new route with param (param will contain the last name)

router.get('/:lastName', properties.findLastName);

You can access the param value like this req.params.lastName in controller

  • Related