Search code examples
javascriptnode.jsregexrestify

Extract a field/property from HTTP referer URL


I have this example URL (referer).

http://172.20.0.83:30923/oauth/authorize?client_id=8193654a-0b63-41df-953e-e6ae10807935&client_secret=somesecret&response_type=code&state=somestate=&redirect_uri=https://somestring.ngrok.io/api/oauthcallback

I need to extract the value of the field 'state'. (which in this case would be 'somestate'). I have attempted to do it with substr() but I have to calculate the length of the base64 encoded substring. (which is not rather dynamic or safe)

As an alternative, I would convert it to JSON and try to extract it from JSON.

Many Thanks.


Solution

  • You need to use Node.js's built in querystring module. You can use it like this:

    var url = require('url');
    var querystring = require('querystring');
    
    var str = 'http://172.20.0.83:30923/oauth/authorize?client_id=8193654a-0b63-41df-953e-e6ae10807935&client_secret=somesecret&response_type=code&state=somestate&redirect_uri=https://somestring.ngrok.io/api/oauthcallback';
    
    var state = querystring.parse(url.parse(str).query).state; // somestate