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. . . . .
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");
}
}
Related
i am trying to get the response from passport.js from node js to react js,i am sending the access and refresh token once user logi's in with google but i am not sure how to take response from node to react
React Code
const googleAuth = async () => {
window
.open('http://localhost:4000/oauth/google', '_self')
};
Node Code
I can able to verify the user and generate access and refresh token but i am not sure how to get these response in react
passport.use(
new GoogleStrategy(
{
clientID: GOOGLE_CLIENT_ID,
clientSecret: GOOGLE_CLIENT_SECRET,
callbackURL: "/google/callback",
},
async function (accessToken, res, refreshToken, profile, done) {
done(null, profile);
const enteredemail = profile.emails.map((a) => a.value);
const sftoken = await getSfToken();
var configHeaders = {
method: "get",
headers: {
Authorization: `Bearer ${sftoken}`,
"Content-Type": `application/json`,
},
};
const emailcheck = await axios.get(
`URL`,
configHeaders
);
if (emailcheck.data.success === true) {
const logintoken = await axios.get(
"URL"
);
const acctok = logintoken?.data?.access_token;
const url = `URL`;
const res = await axios.post(
url,
{},
{
headers: {
Authorization: `Bearer ${acctok}`,
},
}
);
const refreshTokenURL = `URL`;
const refresTok = await axios.get(refreshTokenURL, {
headers: {
Authorization: `Bearer ${acctok}`,
},
});
console.log("refreshToken", refresTok);
} else {
return null
}
}
)
);
passport.serializeUser((user, done) => {
done(null, user);
});
passport.deserializeUser((user, done) => {
done(null, user);
});
I'm trying to call REST API in chrome extension. I managed to get fetch GET working , but couldn't make POST work. The body on server side is always empty. Here is my fetch request:
let url = "http://localhost:3000/api/save/one"
fetch(url, { method: "POST", headers: { "Accept": "application/json", "Content-Type": "application/json; charset=utf-8" }, mode: "no-cors", body: JSON.stringify(json) })
.then(resp => console.log(resp))
When I examined the request on server, I did notice that the content-type on server is always "text/plain;charset=UTF-8". So, my headers doesn't seem to be passed over. However, "Accept" header did go through.
This is the headers on server:
accept:"application/json"
accept-encoding:"gzip, deflate, br"
accept-language:"en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7"
cache-control:"no-cache"
connection:"close"
content-length:"306"
content-type:"text/plain;charset=UTF-8"
If I remove "Accept" from my fetch headers, I got this on server:
accept:"*/*"
accept-encoding:"gzip, deflate, br"
accept-language:"en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7"
cache-control:"no-cache"
connection:"close"
content-length:"306"
content-type:"text/plain;charset=UTF-8"
Any explanation on this? So, how to make POST work?
You need to write the code for post method
Listener
background.js:
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
if (request.contentScriptQuery == "getdata") {
var url = request.url;
fetch(url)
.then(response => response.text())
.then(response => sendResponse(response))
.catch()
return true;
}
if (request.contentScriptQuery == "postData") {
fetch(request.url, {
method: 'POST',
headers: {
'Accept': 'application/json, application/xml, text/plain, text/html, *.*',
'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'
},
body: 'result=' + request.data
})
.then(response => response.json())
.then(response => sendResponse(response))
.catch(error => console.log('Error:', error));
return true;
}
});
Caller
Content_script.js
chrome.runtime.sendMessage(
{
contentScriptQuery: "postData"
, data: JSONdata
, url: ApiUrl
}, function (response) {
debugger;
if (response != undefined && response != "") {
callback(response);
}
else {
debugger;
callback(null);
}
});
Via the code following I get this error:
error: Error: [mobx-state-tree] Cannot modify
'AuthenticationStore#<root>', the object is protected and can only be
modified by using an action.
the code (generator) in question:
.model('AuthenticationStore', {
user: types.frozen(),
loading: types.optional(types.boolean, false),
error: types.frozen()
})
.actions(self => ({
submitLogin: flow(function * (email, password) {
self.error = undefined
self.loading = true
self.user = yield fetch('/api/sign_in', {
method: 'post',
mode: 'cors',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
'user' : {
'email': email,
'password': password
}
})
}).then(res => {
return res.json()
}).then(response => {
self.loading = false // the error happens here!
return response.data
}).catch(error => {
console.error('error:', error)
// self.error = error
})
}), ...
The question: is this not permitted in a generator, is there a better way to update this particular state or does it need to be wrapped by a try/catch?
As always thanks is advance for any and all feedback!
The problem is you're calling then on the Promise returned by fetch(), and the function you pass to then is not an action. Note that functions that run within an action (or flow) do not count as the action itself.
Since you're using yield, you don't need to call then or catch on the Promise returned by fetch(). Instead, wrap it in a try/catch:
submitLogin: flow(function* (email, password) {
self.error = undefined;
self.loading = true;
try {
const res = yield fetch('/api/sign_in', {
method: 'post',
mode: 'cors',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
'user' : {
'email': email,
'password': password
}
})
});
const response = yield res.json();
self.loading = false;
self.user = response;
} catch(error) {
console.log('error: ', error);
self.error = error;
}
}
I want to make an HTTP POST request to a server with credentials (username, password) and content.
More specifically, I used various approaches without success. One of them is:
var request = require('request');
request({
url: 'https://path',
method: 'POST',
auth: {
user: 'username',
pass: 'password'
},
form: {
'grant_type': 'client_credentials',
'text' : 'input-text',
'features': {
'score': true,
}
}
}, function(err, res) {
console.log(res);
var json = JSON.parse(res.body);
console.log("Access Token:", json.access_token);
});
Do you have any suggestion?
I feel more comfortable using promises. request-promise documentation
var request = require('request-promise');
var options = {
method: 'POST',
url: '',
auth: {
user: '',
password: ''
},
headers: {
'': ''
},
json: true
}
return request(options)
.then(function (response) {
// manipulate response
}).catch(function (err) {
return err
})
we have storage array which supports REST API. I am able to do all ( GET/POST/DELETE/PUT) through postman and need to implement one of POST operation through Node.js script.
I am successful in node.js GET operation. But still not able to get the simple POST operation through multiple tries with various forms. here is the codes of both GET and PUT. Also the successful POST operation screenshot by the postman.
Appreciate any help.
GET: Node.js code ( working ):
var request = require('request');
function get_trustyou(trust_you_id, callback){
var options = {
url: 'https://xxxxxx/api/json/v2/types/consistency-groups',
rejectUnauthorized: false,
method: 'GET',
type: 'application/json',
auth:{
user: 'xxxxx',
pass: 'xxx'
}
};
var res = '';
request(options, function ( error, resp, body ) {
if ( !error && resp.statusCode == 200){
res = body;
}
if (error) {
console.log("this is error" + error);
}
callback(res);
});
}
get_trustyou("674fa44c-1fbd-4275-aa72-a20f262372cd", function(resp){
console.log("Here is the result" + resp);
});
POST: Node.js code ( Not working ):
var request = require('request');
function get_trustyou(trust_you_id, callback){
var options = {
body: postData,
url: 'https://xxxx/api/json/v2/types/consistency-groups',
rejectUnauthorized: false,
method: 'POST',
type: 'application/json',
auth:{
user: 'xxxx',
pass: 'xxxxx'
},
form: {
'consistency-group-name': 'TEST-CG'
}
};
request(options, function ( error, resp, body ) {
if ( !error && resp.statusCode == 200){
res = body;
}
if (error) {
console.log("this is error" + error);
}
callback(res);
});
}
get_trustyou("674fa44c-1fbd-4275-aa72-a20f262372cd", function(resp){
console.log("this is the responce" + resp);
});