1

am trying to fetch GTmetrix report using react native

am not good in react native please help me out here

Code:

constructor(props){
    super(props);
    this.state={
      isLoading:true,
        dataSource:null,
        emailAddress: "Your email Address",
        passWord: "your password",
        apikey:'Your api key'
    }
}

async onFetchLoginRecords(props, callback) {
    var data = {
        email: this.state.emailAddress,
        // password: this.state.passWord,
        apikey:this.state.response
       };
       var myurl="https://gtmetrix.com/api/0.1/"
       try {
            const body = new FormData
            body.append("url", "https://example.com/")
            body.append("x-metrix-adblock", "0")
            body.append("", "\\")
            let response = await fetch(
                myurl,
                {
                //parameters: props.params || null,
                method: "POST",
                headers: {
                    "Accept": "application/json",
                    "Content-Type": "multipart/form-data",
                    Authorization: "Your authorization"
                },
                body: JSON.stringify(data)
                }
            );
            if (response.status >= 200 || response.status < 300) {
                alert("authenticated successfully!!!");
                this.fetchapi(myurl);
            }
        } catch (errors) {
            console.log(errors);
        } 
} 
componentWillMount(){
    this.onFetchLoginRecords();
}

fetchapi= (myurl) => {
    fetch(myurl)
    .then(response => response.json())
      .then(response => {
        this.setState({
            isLoading:false,
             dataSource: response.resources
            });
            console.log(response);
      })
    .catch(error=>{
        console.log(error)
    })
}

and i got this result error: [Invalid e-mail and/or Api key] i dint understand after writing correct e-mail and Api key and password. . . . .

enter image description here

Sagar Mistry
  • 131
  • 11

1 Answers1

0

This is really late but the documetation stated

The GTmetrix API uses HTTP Basic Access Authentication as its authentication mechanism. Use your e-mail address as the username and the API key as the password.

to do this using the fetch api replace your header.Authorization : "Your Authorization"

headers: {
  "Accept": "application/json",
  "Content-Type": "multipart/form-data", 
  Authorization: "Your authorization"
},

with

 Authorization: `Basic ${encodeBase64(`${username}:${key}`)}`,

where encodeBase64 is a function

/**
 * Encode a string of text as base64
 * @param {string} data The string of text.
 * @returns {string} The base64 encoded string.
 */
function encodeBase64(data) {
    if (typeof btoa === "function") {
        return btoa(data);
    } else if (typeof Buffer === "function") {
        return Buffer.from(data, "utf-8").toString("base64");
    } else {
        throw new Error("Failed to determine the platform specific encoder");
    }
}
Chris Josh
  • 389
  • 3
  • 7
  • I referenced the encode function from [kraenhansen](https://stackoverflow.com/users/503899/kraenhansen) or goto this post https://stackoverflow.com/questions/2820249/base64-encoding-and-decoding-in-client-side-javascript – Chris Josh Aug 31 '20 at 02:07