Reputation: 599
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
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
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.
So, If you are having any data in the fragment, then it is up to you to process that data (AJAX)
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
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