user3180402
user3180402

Reputation: 599

Fetch the value from url

I have to extract the access token value from the following url.

http://localhost:4001/app1/#access_token=FH2yCAcgmPjMOtKcp3DE&refresh_token=pjgTyaj

How can I fetch the full url and get the access_token value using connect in node.js? I tried using req.url and req.query to get the full url.

Upvotes: 0

Views: 3141

Answers (3)

pgreen2
pgreen2

Reputation: 3651

As per nodejs url with hash, the hash portion of a url is NOT sent to the server. You should try sending the access_token by query.

Upvotes: 1

Amol M Kulkarni
Amol M Kulkarni

Reputation: 21629

Update:

The http client removes # fragments of a url before it queries the server for the page, so the server never has access to it, that's only available to the browser.


When an agent (Browser) requests a resource from a server, the agent sends the only URI to the server (not the fragment). Instead, the agent waits for the server to send the response, then the agent processes the resource according to the document type and fragment value. [[source][1] & for more info here is a [link][2]]

So, If you are having any data in the fragment, then it is up to you to process that data (AJAX)


You can think to grab the hash at client JavaScript (`window.location.hash`) and send it to serve. In case you get string like that, here is an example:
var req_url = 'http://localhost:4001/app1/#access_token=FH2yCAcgmPjMOtKcp3DE&refresh_token=pjgTyaj';
HashKeyValueParsed_JSON = {};
require('url').parse(req_url).hash.substring(1).split('&').forEach(function (x) {
    var arr = x.split('=');
    arr[1] && (HashKeyValueParsed_JSON[arr[0]] = arr[1]);
});
console.log(HashKeyValueParsed_JSON); //Output JSON: { access_token: 'FH2yCAcgmPjMOtKcp3DE',  refresh_token: 'pjgTyaj' }

You will get output:

{ access_token: 'FH2yCAcgmPjMOtKcp3DE',
  refresh_token: 'pjgTyaj' }

I recommend you to keep all your require out of loop or any functions because it a blocking call in Node.js (even though it uses cache[here is a source link]). For more information you can read this answer.

Upvotes: 1

pgreen2
pgreen2

Reputation: 3651

The part of the url that starts with # is referred to as the fragment identifier, or hash. Parsing the url will yield the hash.

If req.url returns 'http://localhost:4001/app1/#access_token=FH2yCAcgmPjMOtKcp3DE&refresh_token=pjgTyaj', then require('url').parse(req.url) returns

{ protocol: 'http:',
  slashes: true,
  auth: null,
  host: 'localhost:4001',
  port: '4001',
  hostname: 'localhost',
  hash: '#access_token=FH2yCAcgmPjMOtKcp3DE&refresh_token=pjgTyaj',
  search: null,
  query: null,
  pathname: '/app1/',
  path: '/app1/',
  href: 'http://localhost:4001/app1/#access_token=FH2yCAcgmPjMOtKcp3DE&refresh_token=pjgTyaj' }

So that part you are looking for is in the hash property of the parsed url: require('url').parse(req.url).hash

Upvotes: 0

Related Questions