Return data from method in object - javascript-objects

I have been trying to figure this one out and I'm not getting how to return the data to another method and call it so that I don't have to statically add the data into my request. I keep getting undefined data on my B2C method when I run it for the data returned from this.O_Auth. Any clues?
let obj = {
O_Auth(key, secret) {
const key = Key;
const secret = Secret;
const auth = "Basic " + new Buffer(key + ":" + secret).toString("base64");
request(
{
uri: "https://randomurl",
method: 'GET',
headers: {
"Authorization": auth
}
},
(err, res, body) => {
if (err) {
return err;
} else {
// console.log(body);
let response = JSON.parse(body);
let res = JSON.stringify(response.access_token)
return res;
}
}
);
},
B2C(params) {
console.log("Random " + this.O_Auth('first', 'second'));
let options = {
method: 'POST',
uri: 'https://randomurl',
headers: {
"Authorization": "Bearer " + this.O_Auth('first', 'second'),
"Content-Type": "application/json"
},
body: {
//values
},
json: true
};
rp(options)
.then(function (body) {
console.log(body);
})
.catch(function (err) {
console.log(err);
});
}
}

Ended up figuring out the asynchronous nature of JavaScript meant I was requesting data that was being evaluated later so I used a promise to get the data and output it first before using it in a subsequent promise that outputs the body. Changed the first request to request promise (rp) that returns the options that will be needed for that promise in the second method.
let obj = {
O_Auth(Key, Secret) {
const key = Key;
const secret = Secret;
const auth = "Basic " + new Buffer(key + ":" + secret).toString("base64");
let options = {
uri: "https://randomurl",
headers: {
"Authorization": auth
},
json: true
};
return rp(options)
},
B2C(param1, param2, param3...) {
this.O_Auth('first', 'second'))then(response =>{
let token = response.access_token;
let options = {
method: 'POST',
uri: 'https://randomurl',
headers: {
"Authorization": "Bearer " + token,
"Content-Type": "application/json"
},
body: {
//values
},
json: true
};
rp(options)
.then(function (body) {
console.log(body);
})
.catch(function (err) {
console.log(err);
});
}).catch(error => console.log(error));
}
}

Related

How to return const from react axios function in another file? [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 1 year ago.
I have a file with form to call a submit function in another file.
And I would like to retrieve the response of the request to use it in file 1.
How can I do that ?
First file form.js
handleSubmit(event, user,props) {
event.preventDefault();
const nomAppartement = event.target.nomAppartement.value;
const superficieAppartement = event.target.superficieAppartement.value;
const newAppartementTableau = {
nom: nomAppartement,
};
newAppartement(newAppartementTableau);
const messageRequest = ??;
Second file data.js
export function newAppartement(newAppartementTableau) {
axios({
method: "post",
url: urlAxiosAppartement,
timeout: 1000 * 5, // Wait for 5 seconds
headers: {
"Content-Type": "application/json",
Authorization: "Bearer " + "****"
},
data: {
fields: {
nom: newAppartementTableau.nom
}
}
})
.then((response) => {
return response;
})
.catch((err) => {
return err;
});
}
You are not returning anything in your function, you're just making an axios call. To solve this add this :
export function newAppartement(newAppartementTableau) {
return axios({
method: "post",
url: urlAxiosAppartement,
timeout: 1000 * 5, // Wait for 5 seconds
headers: {
"Content-Type": "application/json",
Authorization: "Bearer " + "****"
},
data: {
fields: {
nom: newAppartementTableau.nom
}
}
})
.then((response) => {
return response;
})
.catch((err) => {
return err;
});
}
in your first file
newAppartement(newAppartementTableau).then(res => console.log(res.data).catch(e => console.error(e));
You need to wait for the function to finish using await async:
async handleSubmit(event, user,props) {
event.preventDefault();
const nomAppartement = event.target.nomAppartement.value;
const superficieAppartement = event.target.superficieAppartement.value;
const newAppartementTableau = {
nom: nomAppartement,
};
const response = await newAppartement(newAppartementTableau);
and in second file you can return a promise like this:
export function newAppartement(newAppartementTableau) {
return axios({
method: "post",
url: urlAxiosAppartement,
timeout: 1000 * 5, // Wait for 5 seconds
headers: {
"Content-Type": "application/json",
Authorization: "Bearer " + "****"
},
data: {
fields: {
nom: newAppartementTableau.nom
}
}
})
.then((response) => {
return response;
})
.catch((err) => {
return err;
});
}

Can't send image to azure API

I'm making OCR app using amazon. App I'm doing using react native. And I have an error on the moment when I send data.
Error:
{
"code": "InvalidImageUrl",
"requestId": "c495b0d7-a65a-4138-97a9-2b1cb25dced8",
"message": "Image URL is badly formatted."
}
Why? What am I doing wrong? Code:
// ...
selectImage() {
ImagePicker.showImagePicker(options, (response) => {
if (response.didCancel) {
console.log('User cancelled image picker');
} else if (response.error) {
console.log('ImagePicker Error: ', response.error);
} else if (response.customButton) {
console.log('User tapped custom button: ', response.customButton);
} else {
const source = { uri: response.uri };
this.setState({ imageSource: source });
this.extractText(response.uri);
}
});
}
extractText = async (imageSource) => {
// alert(imageSource)
let subscriptionKey = ['CODE'];
let endpoint = ['ENDPOINT']
if (!subscriptionKey) { throw new Error('Set your environment variables for your subscription key and endpoint.'); }
var uriBase = endpoint + "vision/v2.1/ocr";
// Request parameters.
// Display the image.
var sourceImageUrl = imageSource;
const data = new FormData();
data.append(imageSource);
fetch(uriBase + "?" + {
"language": "unk",
"detectOrientation": "true",
},
{
method: 'POST',
headers:
{
'Content-Type': 'application/json',
'Ocp-Apim-Subscription-Key': subscriptionKey,
},
body: '{"url": ' + '"' + data + '"}',
}).then((response) => response.json()).then((data) =>
{
console.log(JSON.stringify(data, null, 2));
}).catch((error) =>
{
console.log(error);
});
};
}
export default ImagePickerScreen;
Based on your code,there is something wrong with your data,it should an image URL so that Azure Version service can access it . I am not quite sure that how you get data in your custom logic . But anyway , this snippet below works , pls have a try :
const data = 'https://stanstroage.blob.core.windows.net/container2/personPic.jpg';
let subscriptionKey = '<key>';
let endpoint = '<endpoint>';
if (!subscriptionKey) { throw new Error('Set your environment variables for your subscription key and endpoint.'); }
var uriBase = endpoint + "vision/v2.1/ocr";
fetch(uriBase + "?" + {
"language": "unk",
"detectOrientation": "true",
},
{
method: 'POST',
headers:
{
'Content-Type': 'application/json',
'Ocp-Apim-Subscription-Key': subscriptionKey,
},
body: '{"url": ' + '"' + data + '"}',
}).then((response) => response.json()).then((data) =>
{
console.log(JSON.stringify(data, null, 2));
}).catch((error) =>
{
console.log(error);
});
Result:
If you want to upload a local image, you should use application/octet-stream as request content-type and set image content buffer as request body.
You can use react-native-fs to read your local image content and use buffer to get image content buffer and post it to Azure side , try snippet below below :
let subscriptionKey = '<key>';
let endpoint = '<endpoint>';
let fileUri = '<fileUri>';
let base64 = await fs.readFile(fileUri, 'base64');
let data = Buffer.from(base64, 'base64');
console.log(data);
if (!subscriptionKey) { throw new Error('Set your environment variables for your subscription key and endpoint.'); }
var uriBase = endpoint + "vision/v2.1/ocr";
fetch(uriBase + "?" + {
"language": "unk",
"detectOrientation": "true",
},
{
method: 'POST',
headers:
{
'Content-Type': 'application/octet-stream',
'Ocp-Apim-Subscription-Key': subscriptionKey,
},
body: data,
}).then((response) => response.json()).then((data) =>
{
console.log(JSON.stringify(data, null, 2));
}).catch((error) =>
{
console.log(error);
});
Result :

How to make common API call function using fetch

I am trying to make common function which will handle all of my API calls from anywhere
I am using react": "^16.8.6" and fetch for making api call
So far what i have figure out to do
is
Helper.js
export function ApiHelper(url, data = {}, method = 'POST') {
let bearer = 'Bearer ' + localStorage.getItem('user_token');
var promise = fetch(url, {
method: method,
withCredentials: true,
// credentials: 'include',
headers: {
'Authorization': bearer,
'X-FP-API-KEY': 'chaptoken',
'Content-Type': 'application/json'
}
})
.then(res => res.json())
.then(
(result) => {
console.log(result);
},
(error) => {
error = error;
}
)
}
export function AnyOtherHelper() {
return 'i am from helper function';
}
And here is from where i am calling this function
componentDidMount() {
let url = `http://localhost/project/api/getdata`;
let op = ApiHelper(url);
}
when I console result in then i am getting appropriate result but what i want to return that response how can i do this part is troubling me
Even i have try to store the result in global variable and it is not working.
Also i have to return the response only when promise is resolved.
You are making an async call from your helper function which means, you will have to return promise from your helper function like this -
export function ApiHelper(url, data = {}, method = 'POST') {
let bearer = 'Bearer ' + localStorage.getItem('user_token');
return fetch(url, { // Return promise
method: method,
withCredentials: true,
// credentials: 'include',
headers: {
'Authorization': bearer,
'X-FP-API-KEY': 'chaptoken',
'Content-Type': 'application/json'
}
})
.then(res => res.json())
.then((result) => {
console.log(result);
return result;
}, (error) => {
error = error;
})
}
USAGE
componentDidMount() {
let url = `http://localhost/project/api/getdata`;
ApiHelper(url)
.then(resposnse => {
console.log(resposnse);
});
}

How to use post method in react native?

constructor(props) {
super(props);
this.state = {text: this.props.navigation.state.params.text,
name:this.props.navigation.state.params.name};
}
manage = () => {
Alert.alert('done')
Actions.reset('mainScreen');
fetch("http://ip/api/confirm", {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify({
name: this.props.navigation.state.params.name,
text:this.props.navigation.state.params.text
})
})
.then(response => response.json())
.catch(error => {
console.error(error);
});
}
i want to do this
when i press in button go to manage function
and post the text and the name to my api i dont know how can i pass them
its give me this error :
network request failed
any help please
I recommend you to use axios to make network requests.
Installing:
npm i -S axios
Performing a POST request:
import axios from 'axios';
axios({
url: 'http://ip/api/confirm',
method: 'post',
data: {
name: this.props.navigation.state.params.name,
text: this.props.navigation.state.params.text,
},
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
var resp = await manage(this.props.session.userId,this.props.session.ApiKey,"hi","hello");
if (resp.status == 200){
var respBody = await resp.json();
console.log('Fetch Todo response '+respBody);
}
API in separate file
export async function manage(userId,ApiKey,query,query1) {
var url ="http://www.example.com/getdata";
const params = {
search:query,
searches:query1
};
var formBody = [];
for (const property in params) {
const encodedKey = encodeURIComponent(property);
const encodedValue = encodeURIComponent(params[property]);
formBody.push(encodedKey + "=" + encodedValue);
}
formBody = formBody.join("&");
const requestOptions = {
'method': 'POST',
'headers': {
'Content-Type': 'application/x-www-form-urlencoded'
// 'Content-Type': 'application/json'
},
'body': formBody
};
requestOptions.headers["userid"] = userId
requestOptions.headers["apikey"] = ApiKey
try {
var resp = await fetch(url, requestOptions);
return resp;
}
catch (err) {
console.log("Request Failed: " + err);
return err;
}
}

How to add Function in POST Headers

The target is sending a POST request with Autorization header contains token.
It's function:
export function authHeader() {
// return authorization header with jwt token
let user = JSON.parse(localStorage.getItem('user'));
if (user && user.token) {
return { 'Authorization': 'Bearer ' + user.token };
} else {
return {};
}
}
Here is async function send to server:
export async function submitToServer(values){
try{
let response = await fetch('http://localhost:50647/fund/submitfund', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type' : 'application/json',
authHeader()
},
body: JSON.stringify(values),
});
let responseJson = await response.json();
return responseJson;
} catch (error) {
console.error(error);
}
}
How can I add authHeader() to headers in POST to correctly authorize this request?
Use ... spread operator like, ...authHeader(). Your authHeader function returns an object { 'Authorization': 'Bearer ' + user.token } or {}. What you want is to merge it to the object you attached with the headers key, so ... operator is the correct tool here.
So your code will be:
export async function submitToServer(values) {
try {
let response = await fetch('http://localhost:50647/fund/submitfund', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
...authHeader()
},
body: JSON.stringify(values),
});
let responseJson = await response.json();
return responseJson;
} catch (error) {
console.error(error);
}
}

Resources