Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Express JS url parameter variable issue

I have this user route

const express = require('express');
const router = express.Router();

const {
    GetAll,
} = require('../areas/directory/controllers/usercontroller');


router.route('/getall?:username&:email').get(GetAll);


module.exports = router;

When I try to access the url in Postman like this: http://localhost:5000/api/user/getall?username=nameone&email=emailone

I get this error: Cannot GET /api/user/getall

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

But, if I change it to

router.route('/getall/:username&:email').get(GetAll);

and access the url in Postman like this: http://localhost:5000/api/user/getall/username=nameone&email=emailone

it works.

On the other hand, even if it works, I am unable to get the value of my variable.

var username = req.params.username;

will return username=nameone instead.

>Solution :

For "http://localhost:5000/api/user/getall?username=nameone&email=emailone" to work, you should change "router.route(‘/getall?:username&:email’).get(GetAll);" to "router.route(‘/getall’).get(GetAll);"
and use req.query.username to access the value of username query parameter and req.query.email to access the value of email query parameter.
After making these changes, you can call "http://localhost:5000/api/user/getall?username=nameone&email=emailone" in Postman, you will be able to see the value of username and email in your code.

This is because you need not have to specify the query parameters in the path, like ?:username in router.route(‘getall’).

EDIT: Adding few more details about path and query,

Please see the top 2 solutions for this question to learn more about path and query and why you should change your code to the way I mentioned above -> Node.js: Difference between req.query[] and req.params

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading