我正在尝试使用react native获取GTmetrix报告
我不擅长原生反应,请在这里帮助我
代码:
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)
})
}我得到了这个结果错误:无效的电子邮件和/或Api密钥,我无法理解写了正确的电子邮件和Api密钥和密码。。。。。

发布于 2020-08-31 10:06:09
这真的很晚了,但纪录片说
GTmetrix API使用HTTP Basic Access Authentication作为其身份验证机制。使用您的电子邮件地址作为用户名,使用API密钥作为密码。
要使用fetch api执行此操作,请替换您的header.Authorization:"Your Authorization"
headers: {
"Accept": "application/json",
"Content-Type": "multipart/form-data",
Authorization: "Your authorization"
},使用
Authorization: `Basic ${encodeBase64(`${username}:${key}`)}`,其中encodeBase64是一个函数
/**
* 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");
}
}https://stackoverflow.com/questions/53737932
复制相似问题