Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I get a parameter from an API response URL?

Currently i am running a fetch call like this

const url = "https://urlhere.com/initAPP/oauth2/authorize";

    fetch(url, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        "client_id": process.env.REACT_APP_CLIENT_ID,
        "response_type": "code",
        "provision_key": process.env.REACT_APP_PROVISION_KEY,
        "authenticated_userid": process.env.REACT_APP_AUTHENTICATED_USERID 
      })
    })
      .then((response) => response.json())
      .then((data) => {
        console.log(data);

        const redirect_uri = data.redirect_uri.toString();
        const urlParams = new URLSearchParams(redirect_uri);
        const code = urlParams.get('code')
       
        
        
      } 
    )

so it all works fine until we try the url params. when i console log Data it returns like this:

redirect_uri : "https://sitehere.sitehere.com?code=U78StlK6sN3hD9CO4ZogvpXvxezFSGU0"

when i console log the redirect_uri variable it prints out only the URL so that works fine

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

but when i try to deconstruct that URL that is returned with the url params part and try to get the CODE parameter in that url it just returns null. How can i get that specific parameter? am i not using the right variable?

Thanks!

>Solution :

You are passing in the full URL to URLSearchParams, it should take only the query string eg. ?code=U78StlK6sN3hD9CO4ZogvpXvxezFSGU0. You can split this out using URL.

 const redirect_uri = "https://sitehere.sitehere.com?code=U78StlK6sN3hD9CO4ZogvpXvxezFSGU0";
 
let params = (new URL(redirect_uri)).searchParams;

const urlParams = new URLSearchParams(params);
const code = urlParams.get('code')

console.log(code);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading