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?
- It will stringify everything you pass (like numbers and booleans, if any).
- It will include the necessary escape characters (such as %20 for spaces, etc.) and ensure that your string is URL-safe.
- 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.