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));
});
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
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
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.