Ajitej Kaushik
Ajitej Kaushik

Reputation: 944

Combine two urls into one in node.js

I am trying to combine two urls into a single url.

var access_token = 138def4a4e;
var url = "https://graph.facebook.com/app/?access_token=";

I want the final url to be:

url = "https://graph.facebook.com/app/?access_token=[access_token]";

How to do that in node.js? I tried using url. Resolve but it was of no use.

pls help TIA

Upvotes: 2

Views: 2966

Answers (2)

Lord of the Goo
Lord of the Goo

Reputation: 1287

As noted above the selected solution is unsafe.

The following snippet should be preferred:

const accessToken = '138def4a4e';
const someValidUrl = 'https://graph.facebook.com/app/?foo=bar'; // note the querystring param
const url = new URL(someValidUrl);
url.searchParams.append('access_token', accessToken);
console.log(url.href);

As you can notice it's able to manage an Url that contains query parameters and the URLencoding of the querystring params.

Upvotes: 5

iSkore
iSkore

Reputation: 7553

I am assuming your code looks like this:

var access_token = '138def4a4e'
var url = 'https://graph.facebook.com/app/?access_token='

If so, the answer is:

var combined = url + access_token

For a final answer of:

var access_token = '138def4a4e'
var url = 'https://graph.facebook.com/app/?access_token='
url += access_token
console.log(url)

Upvotes: 0

Related Questions