2

I'm start learning about Node.js (with Express.js) and React.js. So I have some question about Express Router

Let's see my part of code

server.js

const app = express();
const apiRouter = require("./Routes/apiRoute");

app.use("/api", apiRouter);

app.listen(3000, () => {
  console.log("application run on port " + 3000);
});

/Routes/apiRoute.js

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

router.route("/user/:id")
    .post((req,res)=>{
        // Do something
    })



router.route("/user/status")
    .post((req,res) => {
        // do something
    });

So. My question is How express route determined which method to go.

From my example code if I send POST request like this http://localhost:3000/api/user/status

express router will see status is :id right ?

in the otherhand if I move route for /user/status up it's will go as I expected right ?

Thank you.

Chanom First
  • 1,074
  • 1
  • 10
  • 22
  • the route match works from top to bottom or first to last, s the URL which first matches will work and search for URL will stop. So u can bring /status URL above – Ronit Mukherjee Aug 08 '19 at 06:27

1 Answers1

0

Express matches route in chronological order.

Express starts to match URL with the first route that has been declared in the script and then moves to the next if it does not match. This is because of the fact that Express is a Javascript framework. The function you pass to a route i.e. (req, res) => {...} is actually a js callback function that would be called if the user hit the route matching the corresponding string declared. And in Javascript, the callback that is set first for an event is called first because these callbacks are maintained in a queue. A queue is FIFO as we all know.

If you want both "/user/:id" and "/user/status" to work, you would have to declare the later one first in your code and then the first one.

UtkarshPramodGupta
  • 5,248
  • 4
  • 21
  • 44