-4

I have a function, which takes a number as an argument. I was wondering how I could use this number to pass into a url which will then be used in a GET request.

Below is some of my code, the {{}} brackets below didn't work, I also tried template literals which for some reason also didn't work 'https://www.mywebsite.com/api/v2/${urlID}/fonts.json'


function getID (ID) {

  var urlID = this.ID;


  var request = require("request");

  var options = {
    method: 'GET',
    url: 'https://www.mywebsite.com/api/v2/{{urlID}}/fonts.json',
 };

  • 1
    Try [template literal](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals) `\`https://www.mywebsite.com/api/v2/${urlID}/fonts.json\`` – User863 Mar 31 '20 at 13:58
  • And falling back onto simple string concatenation did not even occur to you …? – CBroe Mar 31 '20 at 13:58
  • Use the [Querystring module](https://nodejs.org/api/querystring.html) – Kunal Mukherjee Mar 31 '20 at 13:59
  • If you want to vote to close this question as a duplicate, fine, but it isn't just string interpolation. Anyone doing this needs to be reminded to escape their URL data correctly. – Brad Mar 31 '20 at 14:04
  • @KunalMukherjee Querystring isn't appropriate in this case. – Brad Mar 31 '20 at 14:05

1 Answers1

0

For your template to work, you'll need backticks.

`string ${someVariable} another string`

Since you're putting data in a URL, you should also take care to use encodeURIComponent() so that any data is escaped properly for the URL.

Putting it all together:

url: `https://example.com/api/v2/${encodeURIComponent(ID)}/fonts.json`
Brad
  • 159,648
  • 54
  • 349
  • 530