0
votes

I am having a strange problem while writing my api. I am using Nodejs and express. The problem occurs when i try to use GET with parameters.


This is my routes code

    router.get('/addFriends/:email', (req, res, next) =>{
  const email = req.params.email;
  UserSchema.find({email: email}, { "friendsPending.emailSender": 1, _id : 0}, (err, data) =>{
    if(err){
      res.status(404).send(err);
    }else{
      res.status(200).send(data[0]);
    }
  });

});


This is my call in Postman : /users/addFriends?email=a


When running this call, server returns 404 status. It happened even when i tested it with another get call.
Any comments are appriciated, however other POST and GET calls work normally (they use body not parameters). Thanks

3
Side note: What you're doing is not RESTful at all; You might want to change it to router.post('/friends/:email', (req, res, next) => {}) since you're creating a friend association.nicholaswmin
next parameter in your function is not necessary. it's for pass router to other matchable routers.Ali

3 Answers

0
votes

You mixed query params and url params. To make your example working, you need to use /addFriends/[email protected] instead of /users/addFriends?email=a.

If you need to send emails via query params (everything after ?) use req.query in your controller instead of req.params.email.

0
votes

This route definition:

router.get('/addFriends/:email', ...);

expects a URL that looks like this:

/addFriends/someEmail

And, you would use req.params.email to refer to the "someEmail" value in the URL path.

Not what you are trying to use:

/addFriends?email=a

If you want to use a URL such as (a URL with a query parameter):

/addFriends?email=a

Then, you would have a route definition like this:

router.get('/addFriends', ...);

And, then you would refer to req.query.email in the route handler. Query parameters (things after the ? in the URL) come from the req.query object.


In Express, route definitions match the path of the URL, not the query parameters.

0
votes

when you use /addFriends/:param you force the router to match any request tha have a part in path as :param.For example:

/users/addFriends/toFavorates // will **match**
/users/addFriends/toFavorates?email=a // will **match** 
/users/addFriends?email=a // will **not** match

if you want to make :param as optional part of url path put a ? after it

/addFriends/:param?

it will tell express route that :param is an optinal part. See this question express uses path-to-regexp for matching the route paths. read the documentation for more options