Search code examples
javascriptnode.jsapiexpressurl-routing

GET request with parameter dosn't hiting desired route NODE js


The Problem occurs while sending GET or any request with parameters in the URL.

for example my
index.js

const express = require("express");
const bodyParser = require("body-parser");

const app = express();

app.use(bodyParser.urlencoded({ extended: true }));

app.get("/:name", function (req, res) {
    let name = req.params.name;
    console.log("Hello " + name + " from /:name");
    res.send("Hello " + name + " from /:name");
});
app.get("/", function (req, res) {
    console.log("Hello world from /");
    res.send("Hello world from /");
});

app.listen(3000, () => {
    console.log("Server is running on port " + 3000)
});

For http://localhost:3000/ it's working perfectly fine. Home route "http://localhost:3000/"


the Problem is occurring when we try to hit /:name route when we use URL http://localhost:3000/?name=NODE it is going to the same route as above. in /

Home route "http://localhost:3000/?"


But the crazy part is when we put http://localhost:3000/NODE which is simply a new different route that is not implemented.
It is getting the response from :/name which doesn't make any sense. enter image description here


is it a BUG or I am doing something wrong or is it something new I am not aware of?

I am currently using Windows11, this problem also occurs in my friend's PC who uses Ubuntu


Solution

  • When you define route as

    /:name
    

    That's called path parameter and it's used like this :

    GET /yourname
    

    And that's why this works :

    GET /NODE
    

    What you"re using to call the endpoint (?name=xxx) is called query parameter, you can get that name from '/' endpoint like this :

    let name = req.query.name;