0

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

  • 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 Jan 07 '20 at 23:13
  • `next` parameter in your function is not necessary. it's for pass router to other matchable routers. – Ali Jan 07 '20 at 23:36

3 Answers3

0

You mixed query params and url params. To make your example working, you need to use /addFriends/my-email@gmail.com 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.

Ihor Yanovchyk
  • 768
  • 6
  • 13
0

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.

jfriend00
  • 683,504
  • 96
  • 985
  • 979
0

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

Ali
  • 1,528
  • 1
  • 10
  • 12