Not able to use query param with expressJs api in localhost

Viewed 109

In my index.js file

app.use('/api/v1/users', userRouter)

In Router file

router.get("/:id", getUserDataById);

In postman:

My GET URL looks like this: http://localhost:3000/api/v1/users?id=120622

Error it gives:

Cannot GET /api/v1/users

I think, this is how query param should be given according to the docs and tutorials i followed, but this error won't go away.

If i remove query, then other endpoints work perfectly.

I am not able to catch what's going wrong here.

I am stuck with this from last 2 days. Just a hint to resolve this, will help me a lot.

Thanks in advance!

3 Answers

Firstly your index.js and routes.js file is fine now you just need to send request correctly see the req.params is different and the req.query is different

First Way with (Query)

In postman:

http://localhost:3000/api/v1/users?id=120622

Your Index.

app.use('/api/v1/users', userRouter);

In Router file.

router.get("/", getUserDataById);

How did you get that id;

let id = req.query.id;

Second Way with (Params) - Look at the postman URL carefully and at Route

In postman:

http://localhost:3000/api/v1/users/120622

Your Index.

app.use('/api/v1/users', userRouter);

In Router file.

router.get("/:id", getUserDataById);

How did you get that id;

let id = req.params.id;

This is the two-way you can get your id, Let me know if you have any more questions and I'll try to clarify your points with more clarity.

You are not calling API correctly inside the Postman. You should call it like this:

http://localhost:3000/api/v1/users/120622

In the router file, what you are using is Route Parameter where the valid URL would be http://localhost:3000/api/v1/users/120622. for your Postman api to work you should remove :id at router file

Related