0

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

3 Answers3

0

I think you're almost there, but /:name does not match /?name=, but it does match /NODE.

This is exactly what's expected to happen. If this surprised you, go re-read the documentation because it should be pretty clear on this.

Evert
  • 93,428
  • 18
  • 118
  • 189
0

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;
Rami Dridi
  • 311
  • 3
  • 16
0

I think I am confused between query parameters and params.

Let: given this URL http://www.localhost:3000/NODE?a=Debasish&b=Biswas

We will have:

req.query

{
  a: 'Debasish',
  b: 'Biswas'
}

req.params

{
  param1: 'NODE'
}

Here I am sending a query but want to receive params. That is where I go wrong.

For better understanding check :
Node.js: Difference between req.query[] and req.params