How to pass parameters in url using google cloud functions - android

I am using http calls to call a cloud function.
I have a URL in the form
url: 'https://api.shipengine.com/v1/labels/rates/rateid,
Now I need to pass values dynamically in rated whenever the function call happens.
How to pass the value into that URL.
I am attaching my cloud function too.
exports.shipmentlabelwithreturnid = functions.https.onRequest((req, res) => {
var request = require("request");
var rateid = req.body.RateId;
console.log(rateid);
var options = { method: 'POST',
url: 'https://api.shipengine.com/v1/labels/rates/'+ rateid,
headers:
{ 'content-type': 'application/json',
accept: 'application/json'
}
};
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body);
});
});

You should use promises, in your Cloud Function, to handle asynchronous tasks. By default request does not return promises, so you need to use an interface wrapper for request, like request-promise which "returns a regular Promises/A+ compliant promise", as follows:
....
const rp = require('request-promise');
exports.shipmentlabelwithreturnid = functions.https.onRequest((req, res) => {
var rateid = req.body.RateId;
console.log(rateid);
var options = { method: 'POST',
uri: 'https://api.shipengine.com/v1/labels/rates/'+ rateid,
headers:
{ 'content-type': 'application/json',
accept: 'application/json'
}
};
rp(options)
.then(response => {
console.log('Get response: ' + response.statusCode);
res.send('Success');
})
.catch(err => {
// API call failed...
res.status(500).send('Error': err);
});
});
Also, it is important to note that you need to be on the "Flame" or "Blaze" pricing plan.
As a matter of fact, the free "Spark" plan "allows outbound network requests only to Google-owned services". See https://firebase.google.com/pricing/ (hover your mouse n the question mark situated after the "Cloud Functions" title)
Since https://api.shipengine.com is not a Google-owned service, you need to switch to the "Flame" or "Blaze" plan.
On the fact that you have to use promises to handle asynchronous tasks, I suggest that you watch these videos from the Firebase team: https://www.youtube.com/watch?v=7IkUgCLr5oA&t=28s and https://www.youtube.com/watch?v=652XeeKNHSk which explain this key concept.

Related

why am i getting html response as data in GET Request of Restful api in android react native?

i am trying to fetch data using GET method for an Api.
it returns data in json in ios but in android it return html Script as shown in image,
let response = await axios.get('https://xxxxxxxx.com/api/reactappsettings/react_get_all_settings/?insecure=cool',
{headers:{
'Content-Type': 'application/json;charset=UTF-8',
'Accept' : 'application/json',
"Access-Control-Allow-Credentials": true,
},withCredentials:true})
console.log("======>",response);
i am stuck here due to this issue, any solutions?
i also tried using react-native-cookie to handle cookies .
CookieManager.get('https://mvhardhats.com')
.then(async (res) => {
console.log('CookieManager.get =>', res);
await axios.get(
`https://mvhardhats.com/api/reactappsettings/react_get_all_settings/?insecure=cool`,
{
headers: {
Cookie:`visid_incap_2485071=${res.visid_incap_2485071}; incap_ses_882_2485071=${res.incap_ses_305_2485071}`,
},
withCredentials:true
},
).then((data)=>{
console.log(data)
})
// => 'user_session=abcdefg; path=/;'
})
but still it returns html even after i got coockies.
Check the whitelist rule in your application and try this code:
Need to use .json() on the response.
let response = await axios.get('https://mvhardhats.com/api/reactappsettings/react_get_all_settings/?insecure=cool', {
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
}
}).then((response) => response.json())
.then((response) => {
console.log("======>",response);
});

Nativescript don't send header correctly using angular service

When i send a normal get request to my deployed nodejs webserver it tell me there is no cookies sent in the header while i ve already write it in the headers of my api service
my service
constructor(private http: HttpClient, private global: Global) { }
verifAuth() {
return new Promise((resolve, reject) => {
this.http.get(`${this.global.url}verif`, this.global.header)
.toPromise()
.then(res => { resolve(res); })
.catch(err => { reject(err); console.log('err', err) });
});
my declared default header
#Injectable({
providedIn: 'root'
})
export class Global {
url: String; header;
constructor() {
this.url = "https://fmm.etudiant.xyz/";
this.header = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'cookies': `xt=${appSetting.getString('xt')}`,
}),
withCredentials: true
};
}
}
and when i debug the request i found this
request header
i expect that the token must be parsed and get the result of user but the backend server tell that there is no cookies while it work fine with an other website
Sending Cookie in Http request is not yet supported, there is a open feature request at Github.

Including csrf token in a post request from react-native app

I have a react native app that posts and gets data from a remote server. In post, i need to include csrf token to avoid token mismatch errors. This is the backend laravel method
//Android Login
public function androidLogin(){
return response()->json([
'name' => 'Android Login',
'route' => 'androidLogin'
]);
}
This is the react native code(i have stripped out error catching code).
async handleSubmit(){
var me = this.state.message;
console.log('this connected',me);
let response = await fetch('http://not-brusselus.be/androidLogin', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'X-CSRF-TOKEN':'csrf_field()'
},
body: JSON.stringify({
session:{
email: 'chesterfield#gmail.com',
password: '123456',
}
})
});
//let res = await response.text();
if (true) {
console.log(response);
} else {
//Handle error
//let error = res;
//throw error;
}
}
The response shows laravel's token mismatch page. How can i send the csrf token successfully?.
Hang the CSRF token off of the window as defined in your main laravel layout file:
window.Laravel = {
csrfToken: '{{csrf_token()}}'
}
Then just use that in your javascript requests:
...window.Laravel.csrfToken
Edit
To the downvoter: This is literally how Laravel does it out of the box and recommends you do it as well.

How to display server response for HTTP errors in React Native

I'm working on a React Native app. We recently made a change to an API call, where it can respond with 500 and an error message detailing the problem so it can be presented to the user. The API response looks like:
{
"error": ["Renter contact info for User 1 missing"]
}
On the client, we're using the standard fetch() method to asynchronously make our request, and resolving the Promise in order to pull the response object out. When I log the response after a call that should trigger a 500, the object looks like:
{type: "default", status: 500, ok: false, statusText: undefined, headers: Headers…}
Here's our internal request() method we use for all API calls:
export function request(endpoint:string, parameters:Object, method:string = HTTP.get, timeout:number = 3000):Promise{
return new Promise(async (resolve, reject) => {
const payload = {
method,
headers: {
'Accept': CONTENT_TYPE,
'Content-Type': CONTENT_TYPE,
'Authorization': `Basic ${base64.encode(Config.API_TOKEN)}`,
'Auth-Token': await Agents.authToken,
},
body: JSON.stringify(parameters),
}
fetch(apiUrl(endpoint), payload)
.then(response => {
if(!response.ok) {
// ******************
// this is where the 500 error state is caught, but my response object doesn't contain the message sent from the server.
reject(response)
// ******************
}
return response
})
.then(resolve)
.catch(reject)
})
}
How can I ensure the response object contains the error message from the server so I can properly display it to my user?
fetch(apiUrl(endpoint), payload)
.then(response => {
if(!response.ok) {
response.json().then(function(data) {
console.log(data);// your error response
},function(error) {
//json error
});
reject(response)
// ******************
}
return response
})
response is a ReadableStream object. You need to use .json() to parse

React Native fetch, unexpected token

I'm trying to call a simple REST service with fetch api in React Native. I'm running the app on Android.
When I call await response.json() I get
Unexpected token � in JSON at position 0
, I tried also with await response.text(), and I get this text as result:
��Mn�0��B�[C�bn�u��?#�+�bLR�ҌBR.�
�����H�ծ�͛�#?>�g���t�%{���Z��؄u�>fs0]����H��'&��u�Z}��y�Z��2����i�d�G�>����R����6LL{j�j�7\���������d���L.���gٲXv�Lf��g�%T�~�\z�U8E܀���ڭ�c��#[G�;�T�������{�*�9�)��a½
���0�组V:ϒ���/�K��3�ݝ����W: c�^UV#�B�7�#�v
�+WG��#YL�|Ġ>q�=#�J}�3=��Q�]Հup^E�0 ^d'Ա
�^���b�.��2,��g2��R<���_rpV:!��<��^>�����{�e�#7m���nA�;n�������l�o�u��kW���r���
This is the code I'm using:
export function fetchMenu() {
return async(dispatch) => {
try {
dispatch(menuRequest(true));
console.log(Institucion.aplent);
var response = await fetch('http://<page_url>/api/moviles/personalizacion', {
compress: true,
headers: {
'aplentId' : Institucion.aplent,
'Accept-Encoding' : 'gzip,deflate'
}
});
console.log(response);
if(!response.ok) throw Error(response.statusText);
var data = await response.json();
console.log('Data:', data);
dispatch(menuSuccess(data));
}
catch(ex) {
console.log(ex);
dispatch(menuFailure(ex));
}
};
}
Note: I've changed the url to for security reasons, but I have the correct url in code.
I've tried with and without the Accept-Encoding header, the same result.
EDIT
If I disable deflate compression inside my REST API (on the server) it works ok, doesn't fetch support deflate compression?
Add these headers to the fetch call to ensure you receive JSON:
'Content-Type': 'application/json',
'Accept': 'application/json',
I would suggest seeing if it works without explicitly setting compression.
If you don't set the Accept-encoding header, react native should automatically zip and unzip it. So probably let it handle it. Instead try changing it to Accept header
export function fetchMenu() {
return async(dispatch) => {
try {
dispatch(menuRequest(true));
console.log(Institucion.aplent);
var response = await fetch('http://<page_url>/api/moviles/personalizacion', {
headers: {
'aplentId' : Institucion.aplent,
'Accept' : 'application/json'
}
});
console.log(response);
if(!response.ok) throw Error(response.statusText);
var data = await response.json();
console.log('Data:', data);
dispatch(menuSuccess(data));
}
catch(ex) {
console.log(ex);
dispatch(menuFailure(ex));
}
};
}
It was a server side issue, I changed the compression algorithm of the api, and it works well

Categories

Resources