Update API url with new location for result - dynamic

I need to update the coordinates on the API-url depending on where the Map centre is located. I did find a way using 'moveend' and map.getCenter to update the coordinates when moving the map to another location. I also added the missing string parts to get a full API request (dhl_moveend). Everything looks fine when checking console.log. The reason is using DHL API service it only gives you 50 location point for the latlng coordinates used (hardcoded) and I don't want to be restricted to one location only as I want to see different areas as well. But when using the code below I get following error <!doctype html> "Unexpected token '<'" error, as it's not valid JSON. I guess the response I'm getting from the API endpoint is an HTML page, not a valid JSON object. What is the error in the code for it to run properly?
No problem when using the hardcoded url but changing to "dhl_moveend" instead of dhl_url gives me the error.
var dhl_moveend;
map.on('moveend', function(e) {
dhl_moveend = 'https://api.dhl.com/location-finder/v1/find-by-geo?latitude=' + map.getCenter().lat.toFixed(5) + '&longitude=' + map.getCenter().lng.toFixed(5) + '&providerType=parcel&serviceType=parcel%3Apick-up&radius=100000&limit=100&countryCode=SE';
console.log(dhl_moveend)
});
// API for DHL parcel pickup locations...
const dhl_url = "https://api.dhl.com/location-finder/v1/find-by-geo?latitude=59.32532&longitude=18.10495&providerType=parcel&serviceType=parcel%3Apick-up&radius=100000&limit=100&countryCode=SE"
addDHL()
.then(response => {
console.log('YESS!');
})
.catch(error => console.log(error.message));
async function addDHL() {
const response = await fetch(dhl_moveend, {
method: 'get',
cache: 'no-store',
headers: {
Accept: 'application/json',
'DHL-API-Key': '------'
},
});
const dhl = await response.json();

Using moveend was not such a good idea as you would hit the service limit of api-calls very quickly. I changed the approach to the "overlayadd" instead. By adding the layer to the map it updates the api call with new coordinates. If others looking for something similar then here is my solution....
const dhlUrl = '';
function addDHL(dhlUrl) {
return fetch(dhlUrl, {
method: 'GET',
cache: 'no-store',
headers: {
'Content-Type': 'application/json',
'DHL-API-Key': '--------'
},
})
.then(response => response.json())
.then(dhl => {
let dhlGeoJson = {};
dhlGeoJson['type'] = 'FeatureCollection';
dhlGeoJson['features'] =[];
for (let i = 0; i < dhl.locations.length; i++) {
let x = dhl.locations[i].place.geo.longitude;
let y = dhl.locations[i].place.geo.latitude;
let dhlFeature = {
'type': 'Feature',
'geometry': {
'type': 'Point',
'coordinates': [x, y]
},
'properties': {
'x': dhl.locations[i].place.geo.longitude,
'y': dhl.locations[i].place.geo.latitude,
'address': dhl.locations[i].place.address.streetAddress,
'name': dhl.locations[i].name,
'postalCode': dhl.locations[i].place.address.postalCode,
'city': dhl.locations[i].place.address.addressLocality,
'type': dhl.locations[i].location.type,
}
};
dhlGeoJson['features'].push(dhlFeature);
}
loadDHLdata(dhlGeoJson);
//console.log(JSON.stringify(dhlGeoJson));
})
.catch(error => console.log(error.message));
}
map.on('overlayadd', function(eventLayer){
// add action...
if (eventLayer.name === 'DHL PickupPoints') {
const lat = map.getCenter().lat.toFixed(5);
const lng = map.getCenter().lng.toFixed(5);
const dhlUrl = "https://api.dhl.com/location-finder/v1/find-by-geo?latitude=" + lat + "&longitude=" + lng + "&providerType=parcel&serviceType=parcel%3Apick-up&radius=100000&limit=100&countryCode=SE";
//console.log(dhlUrl)
addDHL(dhlUrl).then(response => {
//handle response
});
}
});

Related

React native im trying to upload image everytime localuri.slpit not defined showing and {_parts:[[]]} and why this _parts coming while sending data

can anyone tell me what wrong with this code im trying to upload image using react-native-image-picker in react native.but it says localUri.split is not defined and sending data shows in inspect element as {_parts:[[]]} and why this _parts coming every post method ...please help me to figure out this..
const takeAndUploadPhotoAsync = async () => {
const token = await AsyncStorage.getItem("userToken");
let result = await launchImageLibrary();
if (result.cancelled) {
return;
}
let localUri = result.uri;
let filename = localUri.split('/').pop().split('#')[0].split('?')[0]
let match = /\.(\w+)$/.exec(filename);
let type = match ? `image/${match[1]}` : `image`;
const url = `/auth/upload-prescription`;
let formData = new FormData();
formData.append("file", { uri: localUri, name: filename, type });
setLoading(true);
const response = await api
.post(url, formData, {
headers: {
Authorization: `Bearer ${token}`,
'Content-Type': 'multipart/form-data',
},
})
.then((res) => {
showMessage({
message: "Your Prescription is Uploaded Successfully",
textStyle: {textAlign:'center'},
type: "success",
backgroundColor: "#202877",
});
})
.catch((error) => {
console.log(error.response);
});
dispatch({
type: "TAKE_AND_UPLOAD_PHOTO_ASYNC",
payload: response,
});
setLoading(false);
};

I'm trying to send an image using formdata and react native fetch and it's working on ios but not on android

I'm trying to send an image from react native to my server using fetch and it's working on ios but not android. i'm testing on physical devices. the error that is returned is a Network Error exception.
Also, I'm using fetch for all of my api calls, and all the POST requests where I'm sending just a JSON body are working fine, even on Android. It's just sending the image using fetch + formData that's not working on Android.
Some things I've tried are (mostly suggestions on other questions similar to this one)
[commenting out flipper in MainApplication][1]: https://stackoverflow.com/a/61126831/2395829
tried working with the XMLHttpRequest object directly
tried removing the headers in the post request
added android:usesCleartextTraffic="true" to AndroidManifest.xml
I've spent a few hours on this but can't get it to work...
It's possible some of the changes I made to AndroidManifest didn't get synced. I ran npm run android after changing file and it said the Gradle sync completed so I don't think that's too likely...
The code snippet below is where the formData object is created and the fetch request sent
const data = new FormData()
data.append('avatar', {
uri: res,
type: 'image/jpeg',
name: 'gravavatar',
uid: userData.id,
imagePos: idx,
})
fetch(global.BASE_URL + '/save_profile_image/' + userData.id + '/' + imagePos + '/no', {
method: 'post',
headers: {
'Accept': 'application/json',
'Content-Type': 'multipart/form-data',
// 'Access-Control-Allow-Origin': '*',
},
// make sure to serialize your JSON body
body: data
}).then(response => {
if (response.ok) {
// do stuff like setState
}
}).catch(err => {
console.log(err)
})
The entire function is below.
const _pickImage = async (idx) => {
try {
let result = null
try {
result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.All,
allowsEditing: false,
aspect: [4, 3],
quality: 0.05,
});
} catch (err) {
console.log('IMAGE FAILED')
console.log(err)
return;
}
if (!result.cancelled) {
let images = [...state.images];
images[idx] = result.uri
if (result.uri.slice(0, 4) == 'file') {
var xhr = new XMLHttpRequest();
xhr.open("GET", result.uri, true);
xhr.responseType = "blob";
xhr.onload = function(e) {
console.log(this.response);
var reader = new FileReader();
reader.onload = async function(event) {
var res = event.target.result;
var stringLength = res.length - 'data:image/png;base64,'.length;
var sizeInBytes = 4 * Math.ceil((stringLength / 3)) * 0.5624896334383812;
var sizeInKb = sizeInBytes / 1000;
// console.log(sizeInKb)
if (sizeInKb > 4999) {
alert('File is too large')
return;
}
const data = new FormData()
data.append('avatar', {
uri: res,
type: 'image/jpeg',
name: 'gravavatar',
uid: userData.id,
imagePos: idx,
})
fetch(global.BASE_URL + '/save_profile_image/' + userData.id + '/' + imagePos + '/no', {
method: 'post',
headers: {
'Accept': 'application/json',
'Content-Type': 'multipart/form-data',
// 'Access-Control-Allow-Origin': '*',
},
// make sure to serialize your JSON body
body: data
}).then(response => {
if (response.ok) {
// do stuff like setState
}
}).catch(err => {
console.log(err)
})
}
var file = this.response;
reader.readAsDataURL(file)
};
xhr.send()
}
return;
}
} catch (E) {
console.log(E);
}
};
Help would be much appreciated.
Thank you.

filter query param not working through axios get from my vue js application?

whenever a user types anything into the textfield, an axios get request to the url
http://sandbox4.wootz.io:8080/api/data/1/action/?filter={id}like'%TE%' is made and it is supposed to return back all the filtered results based on the search(what user has typed) as a response. But currently rather than returning the filtered results as a response it is giving out all results(non-filtered results).
NOTE: I have tested the above mentioned URL through postman by making a get request and it gave out the filtered results perfectly.Why is the same not happening through my application code?plz help
getAsyncDataAction: debounce(function(name) {
if (!name.length) {
this.dataAction = [];
return;
}
this.isFetching = true;
api
.getSearchData(this.sessionData.key,`/action/?filter={id}like'%${name}%'`)
.then(response => {
this.dataAction = [];
response.forEach(item => {
this.dataAction.push(item);
});
console.log('action results are'+JSON.stringify(this.dataAction)) //displays all the results(non-filtered)
})
.catch(error => {
this.dataAction = [];
throw error;
})
.finally(() => {
this.isFetching = false;
});
}, 500),
api.js
import axios from 'axios';
const props = {
base_url: '/api/store',
search_url: '/api/entity/search',
cors_url: 'http://localhost',
oper_url: '/api'
};
axios.defaults.headers.get['Access-Control-Allow-Origin'] = props.cors_url;
axios.defaults.headers.post['Access-Control-Allow-Origin'] = props.cors_url;
axios.defaults.headers.patch['Access-Control-Allow-Origin'] = props.cors_url;
async function getSearchData(key, path) {
try {
console.log('inside getSearchData path value is'+path)
console.log('inside getSearchData and url for axios get is '+props.base_url + '/data' + path)
let response = await axios({
method: 'get',
url: props.base_url + '/data' + path,
headers: {'session_id': key}
});
if (response.status == 200) {
console.log(response.status);
}
return response.data;
} catch (err) {
console.error(err);
}
}
The problem is that you're not encoding the query string correctly. In particular, your % signs need to become %25
To do this, I highly recommend using the params options in Axios.
For example
async function getSearchData(key, path, params) { // 👈 added "params"
// snip
let response = await axios({
method: 'get',
url: `${props.base_url}/data${path}`,
params, // 👈 use "params" here
headers: {'session_id': key}
});
and call your function with
const params = {}
// check for empty or blank "name"
if (name.trim().length > 0) {
params.filter = `{id}like'%${name}%'`
}
api
.getSearchData(this.sessionData.key, '/action/', params)
Alternatively, encode the query parameter manually
const filter = encodeURIComponent(`{id}like'%${name}%'`)
const path = `/action/?filter=${filter}`
Which should produce something like
/action/?filter=%7Bid%7Dlike'%25TE%25'

GraphCool TypeError: Converting circular structure to JSON

I copy-pasted example from official documentation in hope that I will see some different error (invalid URL or invalid auth key or something similar) However I get some webpack/sandbox error:
const fetch = require('isomorphic-fetch')
const Base64 = require('Base64')
const FormData =require('form-data')
const apiKey = '__MAILGUN_API_KEY__'
const url = '__MAILGUN_URL__'
export default event => {
const form = new FormData()
form.append('from', 'Nilan <nilan#graph.cool>')
form.append('to', 'Nikolas <nikolas#graph.cool>')
form.append('subject', 'Test')
form.append('text', 'Hi')
return fetch(url, {
headers: {
'Authorization': `Basic ${Base64.btoa(apiKey)}`
},
method: 'POST',
body: form
})
}
Even simple API requests fail:
require('isomorphic-fetch')
module.exports = function (event) {
const url = 'https://jsonplaceholder.typicode.com/posts'
return fetch(url)
}
The code above also returns:
TypeError: Converting circular structure to JSON
at Object.stringify (native)
at /data/sandbox/lib/sandbox.js:532:48
at /data/io/8e0059b3-daeb-4989-972f-e0d88e27d15e/webtask.js:46:33
at process._tickDomainCallback (node.js:481:9)
How do I successfully call API from custom graphcool subscription/resolver?
This is the simplest working example:
require('isomorphic-fetch')
module.exports = function (event) {
const url = 'https://jsonplaceholder.typicode.com/posts'
return fetch(url)
.then(res => res.json())
.then(data => {
console.log(data)
return {
data: {
sum: 3
}
}
})
}

Create a new script tag (Shopify) Error: Invalid URI "/"

Based on this tutorial, I tried the below code. I'm trying to add a new script to the web page.
request.post(accessTokenRequestUrl, {
json: accessTokenPayload
})
.then((accessTokenResponse) => {
const accessToken = accessTokenResponse.access_token;
// DONE: Use access token to make API call to 'shop' endpoint
const shopRequestUrl = 'https://' + shop + '/admin/shop.json';
const shopRequestHeaders = {
'X-Shopify-Access-Token': accessToken,
'Content-Type': 'application/json'
};
const createScriptTagUrl = 'https://' + shop + '/admin/script_tags.json';
const scriptTagBody = {
"script_tag": {
"event": "onload",
"src": "https:\/\/djavaskripped.org\/fancy.js"
}
}
request.get(shopRequestUrl, {
headers: shopRequestHeaders
})
.then((shopResponse) => {
res.status(200).end(shopResponse);
})
.catch((error) => {
res.status(error.statusCode).send(error.error.error_description);
});
request.post(createScriptTagUrl, {
json: scriptTagBody
}, {
headers: shopRequestHeaders
})
.then((scriptResponse) => {
res.status(200).end(scriptResponse);
})
.catch((error) => {
res.status(error.statusCode).send(error.error.error_description);
});
However, I get RequestError: Error: Invalid URI "/"
Am I missing anything? Or is the src value is having some problem?
I think you are using get method to create the script tag instead of post. Please use post method and also remove \ from the src.
Thanks
Fixed using the below code. Basically, the request body was supposed to be sent as JSON.
request.post({
url: createScriptTagUrl,
body: scriptTagBody,
headers: shopRequestHeaders,
json: true
}, function(error, response, body) {
if (!error) {
console.log(body)
}
});