0

I'm trying to develop a currency converter using node.js. I'm using 'request' to make HTTP requests. Currently in my code, the query strings (q=1, from=USD, to=LKR) are hard coded in the url. I want to know how to pass those strings as arguments in order to make it dynamic and get as many currency formats as I want.

var request = require('request');

const options = {
    url : "https://currency-exchange.p.rapidapi.com/exchange?q=1&from=USD&to=GBP",
    headers: {
      'x-rapidapi-host': 'currency-exchange.p.rapidapi.com',
      'x-rapidapi-key': 'b13c4f3d67msh8143a7f1298de7bp1e8586jsn4453f885a4e7'
    }
  }

function callback(error, response, body) {
  if (!error && response.statusCode == 200) {
    var info = JSON.parse(body);
    console.log(response.body);
  }
}

request(options, callback);
Husnul Aman
  • 489
  • 3
  • 11

2 Answers2

1

You can use the qs parameter in the request library when performing a new request.

As specified here https://stackoverflow.com/a/16903926/7088387

You could use this:

const params = {
  q: 1,
  from: 'USD',
  to: 'GBP'
};

const options = {
    url : "https://currency-exchange.p.rapidapi.com/exchange",
    headers: {
      'x-rapidapi-host': 'currency-exchange.p.rapidapi.com',
      'x-rapidapi-key': 'b13c4f3d67msh8143a7f1298de7bp1e8586jsn4453f885a4e7'
    },
    qs: params
  }

function callback(error, response, body) {
  if (!error && response.statusCode == 200) {
    var info = JSON.parse(body);
    console.log(response.body);
  }
}

request(options, callback);
Alon L
  • 152
  • 1
  • 5
-1

You could have a variable that stores those:

var currencies = ['USD', 'GBP'];

And then just put those variable values into your request string:

url : "https://currency-exchange.p.rapidapi.com/exchange?q=1&from=" + currencies[0] + "&to=" + currencies[1]

You could also use template literals using backticks like so:

url : `https://currency-exchange.p.rapidapi.com/exchange?q=1&from=${currencies[0]}&to=${currencies[1]}`
Jacob Helton
  • 173
  • 9