Glenn Posadas
Glenn Posadas

Reputation: 13283

Node express request goes to other endpoint in router

I can't figure this out. Why is it my request:

localhost:3000/api/customers/search?q=glenn

Goes to:

  // Retrieve a single Customer with customerId
  router.get("/:customerId", customers.findOne);

when it is supposed to go to here???

// Search for a customer.
  router.get("/search/:q", customers.search)

customer.routes.js

module.exports = app => {
  const customers = require("../controllers/customer.controller");

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

  // Create a new Customer
  router.post("/", customers.create);

  // Retrieve all Customers
  router.get("/", customers.findAll);

  // Search for a customer.
  router.get("/search/:q", customers.search)

  // Retrieve a single Customer with customerId
  router.get("/:customerId", customers.findOne);

  // Update a Customer with customerId
  router.put("/:customerId", customers.update);

  // Delete a Customer with customerId
  router.delete("/:customerId", customers.delete);

  // Create a new Customer
  router.delete("/", customers.deleteAll);

  app.use("/api/customers", router)
};

Morgan + Sequelize logs:

Executing (default): SELECT id, email, name, active, createdAt, updatedAt FROM customers AS customer WHERE customer.id = 'search'; ::1 - - [25/Apr/2020:16:41:06 +0000] "GET /api/customers/search?q=glenn HTTP/1.1" 200 0 "-" "PostmanRuntime/7.24.1"

Upvotes: 0

Views: 235

Answers (2)

xdeepakv
xdeepakv

Reputation: 8125

you need another route to handle, search without "/:r".

/search/:q only works for query like

  • /search/test
  • /search/something

Not

  • /search?q=something

Update:

// Search for a customer.
  router.get("/search/:q", customers.search)

// Add this
// Search for a for query.
  router.get("/search", customers.search)

Upvotes: 1

Joe Lissner
Joe Lissner

Reputation: 2472

your request doesn't match what the router is looking for, either change your request from localhost:3000/api/customers/search?q=glenn to localhost:3000/api/customers/search/glenn

OR

change router.get("/search/:q", customers.search) to router.get("/search", customers.search)

Upvotes: 1

Related Questions