Another Weeb
Another Weeb

Reputation: 67

How to Separate routes with and without query param?

Simple question, how can i set the routes so that it goes to the correct route,

app.get("/:post",(req,res) => {})

AND

app.get("/post",(req,res) => {})

This happens when i typed "/post", the server is confused if it should go to "/post" route or "/:post". This applies to routes that is similiar "/publish" "/logout" "/login".

Please share the knowledge on how to fix this, Thanks.

Upvotes: 2

Views: 673

Answers (3)

Nikhil Unni
Nikhil Unni

Reputation: 779

The order of the routes also important in this case. It cabn be solved by defining the route app.get("/post",(req,res) => {}) prior to app.get("/:post",(req,res) => {}). In this case if you called something like http://localhost:3000/..../post sure it will go to the route /post and rest of the calls are to the next route.

.................. app.get("/post",(req,res) => {}) app.get("/:post",(req,res) => {}) ...........................

If we do like above then the server won't get confused I think.

Upvotes: 0

E. Mancebo
E. Mancebo

Reputation: 754

That's because /:post matches the resources that you mention (/post, /publish, /logout etc). To solve this use a noun prior the wildcard, such as /post/:post. In that way, you avoid the ambiguity.

Upvotes: 0

kedar sedai
kedar sedai

Reputation: 1722

If you are using below routes then you need to pass some parameters into your URL

app.get("/:post",(req,res) => {})

But if you are looking for routes that don't return anything from the URL then you used below routes

app.get("/post",(req,res) => {})

So, if you're using 1 route then you need to pass some parameters in your URL

Upvotes: 1

Related Questions