0

I have a webpage that requires token in order to show the page. From the page, if a user click submit button, I am making an API call using ajax. In the parameter, I am not sure how to pass in token parameter used when showing the page.

For example, my webpage url is http://test.com?token=123. The page is loaded with button. When the user click that button, I want to make an API call to http://test2.com but with the token from current page, i.e. 123.

The reason why I want to do is because when I deploy service with multiple pods. I have an authentication service and every time API is called, it runs authentication using the token.

Jonathan Hagen
  • 580
  • 1
  • 6
  • 29
  • You can save token to localstorage, cache or session storage and when you call to test2 check does it exist – Greg-- Jul 26 '21 at 14:34
  • 2
    So read the querystring and append it to the link? https://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript – epascarello Jul 26 '21 at 14:39

1 Answers1

0

you can obtain all the parameters as a string for genera use with this code

this.location.search

and you can use it to create an object that will contain all the parameters keys as keys and the values as values, this code works in all use cases and accepts any given number of parameters.

let parm = window.location.search.slice(1).split('=').join(',').split('&').join(',').split(','),
    obj = Object.fromEntries(new Array(Math.ceil(parm.length / 2)).fill().map(_ => parm.splice(0, 2)))

// get all parameters as an object
console.log(obj)
// Access the value of a parameter
console.log(obj.key)

using the code above you can get your token with

console.log(obj.token)

but if you don't have any use for the full code you can just use a small sample that will work only when you only have one parameter to fetch

this.location.search.split('=').pop();
jadinerky
  • 98
  • 7