Gabriel Brito Gabriel Brito - 4 months ago 47
Node.js Question

Rest api implementation with parameter using JetBrains WebStorm + node.js + express

First of all, i'm using JetBrains WebStorm and used to create the Node.js Express App project.

My modifications were at app.js

app.get('/api/restaurants', function(req, res) {
console.log("Parameter[0]", req.params.restaurant_id);
res.json({
'01010112D8139F13': '0ao123r1'
});
});
app.get('/api/restaurants/:id', function(req, res) {
console.log("Parameter[1]", req.params.restaurant_id);
res.json({
'message': 'worked?'
});
});


I'm using postman plugin at chrome to test my api and i can't access localhost:3000/api/restaurants?restaurant_id=01010112D8139F13 without being routed by router.route('/restaurants') instead of router.route('/restaurants/:restaurant_id')

At console i have:

GET /api/restaurants?id=01010112D8139F13 200 1.803 ms - 31


If anyone can help me, thanks in advance.

Answer

restaurant_id is not a query parameter but a variable part in your path. For example /restaurants/01010112 and /restaurants/1 are both handled by the same Web request handler because both fit on /restaurants/:restaurant_id pattern.

The restaurant specific endpoint need to be modified the following way:

app.get('/api/restaurants/:id', function(req, res) {
  console.log("Parameter[1]", req.params.id);
  res.json({
    'message': 'worked?'
  });
});

And use the following url on the console:

/api/restaurants/01010112D8139F13

Comments