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.
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 /
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.
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
Answers
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
req.params
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
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.
When you define route as
That’s called path parameter and it’s used like this :
And that’s why this works :
What you"re using to call the endpoint (?name=xxx) is called query parameter, you can get that name from ‘/’ endpoint like this :