Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Express GET route will not work with parameters

I am new to Express and Mongoose. I am currently working on my first project, that is not a tutorial, and I has run into a problem.

I have multiple routes, they are defined in the index.js like this:

app.use('/api/client',require('./routes/client'));
app.use('/api/host',require('./routes/host'));

In the routes, there are multiple verbs that work, like PUT and POST. Here is the problematic route (I am trying to do more that what is presented here, but what is presented here, does not work as well):

router.get('/ama/:id', function (req, res, next) {
    Ama.findById(req.params.id).then(function(Ama){
        res.send(Ama);
    });
});

This should work, right? It should return the document in the database, with that id. And I have checked if the document excists, probably around a 100 times. Now, if I simplify the route greatly, removing the id, and make a simple response, the route works:

router.get('/ama', function (req, res, next) {
    res.send({type:"GET"});
});

It's so wierd, that as soon as i add the parameter, i get a:

<pre>Cannot GET /api/host/ama</pre>

in Postman.

Any ideas? Mongod is running, my other routes are working.

like image 344
Andreas Avatar asked Apr 04 '17 13:04

Andreas


1 Answers

It looks like you're trying to retrieve this URL:

/api/host/ama?id=SOMEID

However, you have a route declared for URL's that look like this:

/api/host/ama/SOMEID

In other words, the id is part of the path of the URL, and not passed as a query string parameter (that's what /:id means: it's a placeholder for a part of the URL that the route should match).

So either change the request-URL by adding the id to the path (/api/host/ama/58e395a8c6aaca2560089c‌​e7), or rewrite your route handler to something like this:

router.get('/ama', function (req, res, next) {
    Ama.findById(req.query.id).then(function(Ama){
        res.send(Ama);
    });
});

However, I would advise using the former (making the id part of the URL).

like image 164
robertklep Avatar answered Sep 27 '22 22:09

robertklep