Search code examples
node.jsrestful-url

How to pass multiple parameters into RESTful API for query?


I have a node.js program.

I would like to use this node.js program to perform query like below:

SELECT * from users where uid = ? and role = ?

And I would like to design the URL like below:

http://localhost:4001/api/v1/getUserByUID?uid=XXXXX&role=XXXXX

How can I modify the below coding to achieve my goal?

var express = require('express');
var router = express.Router();


router.get('/api/v1/getUserByUID/:uid', function(req, res, next) {
    connection.query('SELECT * from users where uid = ?', [req.params.uid], function (error, results, fields) {
        if(error){
            res.send(JSON.stringify({"status": 500, "error": error, "response": null})); 
            //If there is error, we send the error in the error section with 500 status
        } else {
            res.send(JSON.stringify({"status": 200, "error": null, "response": results}));
            //If there is no error, all is good and response is 200OK.
        }
    });
});

module.exports = router;

Thank you.


Solution

  • Try this

    var express = require('express');
    var router = express.Router();
    
    
    router.get('/api/v1/getUserByUID', function(req, res, next) {
        connection.query('SELECT * FROM users WHERE uid = ? AND role = ?', [req.query.uid, req.query.role], function (error, results, fields) {
            if(error){
                res.send(JSON.stringify({"status": 500, "error": error, "response": null})); 
                //If there is error, we send the error in the error section with 500 status
            } else {
                res.send(JSON.stringify({"status": 200, "error": null, "response": results}));
                //If there is no error, all is good and response is 200OK.
            }
        });
    });
    
    module.exports = router;
    

    You obviously wanna make sure the query params are sanitized, etc.