Search code examples
node.js

How to pass variables in URL in NodeJS


I am using an API to send SMS I want to pass variables like phone number and message in a URL.

When I am sending variable dynamically then it's not retrieving value of a variable.

Below is my code:

  router.post('/testSms',(req,res) => {

  const phone = req.body.phone;
  const msg  = req.body.message;

  request({
      url:'http://www.techsolver.in/http-api.php?username=abc&password=pwd&senderid=MYID&route=1&number=phone&message=msg',
      method:'GET'
    },function(err,response){
              
        if(err){
            console.log("Error",err);
        }
        else{
            console.log(response);
        }

    });
});

module.exports = router;

Here it's not retrieving values. How can I resolve this issue?


Solution

  • You are not referencing the variables, instead you have used their names as strings in the URL.

    You have to append them in the URL string as query parameters like so:

    'http://www.techsolver.in/http-api.php?username=abc&password=pwd&senderid=MYID&route=1&number=' + phone + '&message=' + msg
    

    You can see the phone and msg are appended in the string as variables instead of just being written in the string, The complete code would be:

    router.post('/testSms',(req,res) => {
    
      const phone = req.body.phone;
      const msg  = req.body.message;
    
      request({
          url:'http://www.techsolver.in/http-api.php?username=abc&password=pwd&senderid=MYID&route=1&number=' + phone + '&message=' + msg,
          method:'GET'
        },function(err,response){
    
            if(err){
                console.log("Error",err);
            }
            else{
                console.log(response);
            }
    
        });
    });
    
    module.exports = router;
    

    Alternatively, you can check out Anuj Pancholi's answer that touches upon template literals, and the use of the querystring module of nodejs.