1

I'm new to nodejs and express and trying to build a simple functionality

I have this piece of code which successfully sends my get requests to the appropriate route (in this case a service where I have a mysql query written)

app.get('/requests', service.getRequests);

This works with simple get request like http://localhost:5000/requests

I'm wondering how I can get a parameter from the get request and pass it in the route handler ?

For example: something like http://localhost:5000/requests?id=123 I'd like to pass in the id to the service.getRequests function, but the below doesn't work -

app.get('/request',function(req,res){
  res.send(service.getRequests(req));
});

Here's how service.js (part of it) looks like

exports.getRequests = function(req,res){
  //console.log(req.id);
  connection.connect()
  connection.query('SELECT * FROM table1 t where t.uid = ? LIMIT 10',[req.id], function (err, result, fields) {
    if (err) throw err
    res.json({ results: result });
  })
  connection.end()
}

EDIT : My question specifically is not how to get a GET parameter but how do I use it with res.send / call a service with this parameter, specifically the below line -

app.get('/request',function(req,res){
  res.send(service.getRequests(req));
});
Nash3man
  • 155
  • 1
  • 4
  • 15
  • Possible duplicate of [How to get GET (query string) variables in Express.js on Node.js?](https://stackoverflow.com/questions/6912584/how-to-get-get-query-string-variables-in-express-js-on-node-js) – Andy Taton Aug 29 '18 at 18:14
  • Hi @AndyTaton thank you for the response. My question however is not how to get the GET variables but how could I pass them in as a parameter to another service, specifically, looking for some validation to this piece of code - app.get('/request',function(req,res){ res.send(service.getRequests(req)); }); – Nash3man Aug 29 '18 at 18:17

2 Answers2

3

You can configure your endpoint to take a variable like this

http://localhost:5000/requests/123

app.get('/request/:id',function(req,res){
    const id = req.params.id;
    console.log(id); // should display 123
});
Chris
  • 681
  • 1
  • 6
  • 16
  • Thank you so much for the answer. My specific question is, once I extract the id, is this the right way to send the id to the service ? - app.get('/request/:id',function(req,res){ const id = req.params.id; console.log(id); // should display 123 res.send(service.getRequests(req));}); – Nash3man Aug 29 '18 at 18:20
0

It's not clear which node module you're using to send queries to PostgreSQL. But, assuming you're using pg, then the problem is you should put the param as follows:

SELECT * FROM table1 t where t.uid = $1 LIMIT 10

Bruno Paulino
  • 56
  • 1
  • 2