Digvijay
Digvijay

Reputation: 3281

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?

Upvotes: 0

Views: 11090

Answers (4)

Waqas Javed
Waqas Javed

Reputation: 424

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.

Upvotes: 4

Anuj Pancholi
Anuj Pancholi

Reputation: 1213

One way to do it is using template literals, which has been discussed in other answers (I encourage you to check out the link shared by Jason).

const phone = "1234567890";
const message = "my-message-content";

const url = `http://www.techsolver.in/http-api.php?username=abc&password=pwd&senderid=MYID&route=1&number=${phone}&message=${message}`

console.log(url);

However, if you're using passing query parameters in a URL in Node.js, I highly recommend that you use the querystring module which is a core module of Node.js, that has a stringify function for exactly this purpose.

The docs for this are at: https://nodejs.org/api/querystring.html#querystring_querystring_stringify_obj_sep_eq_options

You simply make an object with the keys as the parameter names and the values as the values you wish to pass, and querystring.stringify() will form a querystring for you which you can just append at the end of the url.

const querystring = require('querystring');
console.log(querystring.stringify({
    phone: "1234567890",
    message: "your message content"
}))

The output for this should be phone=1234567890&message=your%20message%20content.

Your code will look something like:

const querystring = require('querystring');

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

    const paramsObject = {
        username: "abc",
        password: "pwd",
        senderid: "MYID",
        route: 1,
        number: req.body.phone,
        message: req.body.message
    }

    const myQueryString = querystring.stringify(paramsObject);

    request({
        url: `http://www.techsolver.in/http-api.php?${myQueryString}`,
        method: 'GET'
    }, function(err, response) {

        if (err) {
            console.log("Error", err);
        } else {
            console.log(response);
        }

   });
});

So why should you involve this module instead of making the seemingly simple string yourself?

  1. It will stringify everything you pass (like numbers and booleans, if any).
  2. It will include the necessary escape characters (such as %20 for spaces, etc.) and ensure that your string is URL-safe.
  3. Say there's a situation where you only want to pass params which are available. It may also be that you have to pass no params. Where should you include the "&" character? Should you include it before every new key value pair? But then you'll have to check for the first parameter and make sure the & is not included in it, else your string will be URL?&key=value, which is wrong. So you choose to append it after each key value pair, but then you'll have to check for the last param, else your URL will end with a "&" and will expect another param which doesn't exist, so that's also wrong. The querystring module will take care of all this for you.

Upvotes: 2

Naor Levi
Naor Levi

Reputation: 1823

Use string formatting:

  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;

Upvotes: 1

Jason
Jason

Reputation: 734

You're sending "phone" as the value of number in your request, instead of passing the value of the variable phone

The easiest way to solve this is with template literals
http://www.techsolver.in/http-api.php?username=abc&password=pwd&senderid=MYID&route=1&number=${phone}&message=${msg}

Upvotes: 2

Related Questions