0

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.

Newbiee
  • 103
  • 1
  • 2
  • 11
  • 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) – Sahil Apr 01 '18 at 09:45
  • In your code, `:uid` gets mapped to a [route parameter](https://expressjs.com/en/guide/routing.html#route-parameters). Based on the URL you mentioned, you want to change the route URL to `/api/v1/getUserByUID` and follow the link @Sahil posted. – fardjad Apr 01 '18 at 10:48

1 Answers1

2

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.

alizahid
  • 959
  • 6
  • 17