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

Time:11-03

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

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!

CodePudding user response:

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);

CodePudding user response:

You need to create a URL object and use the search to get that value. Something like this

const url = new URL(data.redirect_url.toString());
const params = new URLSearchParams(url.search);
const code = params.get('code');
  • Related