JSON api works on local, but not on public deploy - json

I have a weather API using JSON that works on my local machine, but when I try to deploy it to GithubPages, it nulls out and the API doesn't pull. It was written in js for a reactjs page.
Here is the working site that is on localhost:3000
Not working website hosted on GitHub pages
Deployed Website
state = {
current: 'none'
}
fetchWeather = () => {
return fetch(`https://api.aerisapi.com/observations/75248client_id=${accessId}&client_secret=${APIkey}`)
.then((res) => res.json())
}
componentDidMount = () => {
this.fetchWeather()
.then((json) => {
json.success ? this.setState({ current: json.response.ob }) : null
})
}
formatCurrentWeather = (currentWeather) => {
let current = ''
if (currentWeather.toLowerCase().charAt(currentWeather.length-1) === 'y') {
current = currentWeather.toLowerCase() + ' '
} else if (currentWeather.toLowerCase() === 'clear') {
current = 'cloudless '
} else if (currentWeather.toLowerCase() === 'freezing fog') {
current = 'freezing '
} else if (currentWeather.toLowerCase().charAt(currentWeather.length-1) === 'g') {
current = currentWeather.toLowerCase() + 'gy '
} else {
current = currentWeather.toLowerCase() + 'y '
}
return current
}
importAll = (r) => {
let icons = {};
r.keys().map((item, index) => { icons[item.replace('./', '')] = r(item); });
return icons;
}
render() {
console.log(this.state.current)
const icons = this.importAll(require.context('../images/icons', false, /\.(png|jpe?g|svg)$/));
let currentWeather = '🌃'
this.state.current === 'none' ? null : currentWeather = this.formatCurrentWeather(this.state.current.weatherPrimary)

Related

strapi version 4 flatten complex response structure

Use this function to flatten the response returned from strapi on version 4. Helps you get rid of data and attributes properties
This will give you the same response structure as version 3 of strapi. This would help you migrate to version 4 from version 3 easily.
How to use it?
import the file.
const flattnedData = flattenObj({...data})
NOTE: The data here is the response returned from strapi version 4.
export const flattenObj = (data) => {
const isObject = (data) =>
Object.prototype.toString.call(data) === "[object Object]";
const isArray = (data) =>
Object.prototype.toString.call(data) === "[object Array]";
const flatten = (data) => {
if (!data.attributes) return data;
return {
id: data.id,
...data.attributes,
};
};
if (isArray(data)) {
return data.map((item) => flattenObj(item));
}
if (isObject(data)) {
if (isArray(data.data)) {
data = [...data.data];
} else if (isObject(data.data)) {
data = flatten({ ...data.data });
} else if (data.data === null) {
data = null;
} else {
data = flatten(data);
}
for (const key in data) {
data[key] = flattenObj(data[key]);
}
return data;
}
return data;
};
In my case I created a new middleware "flatten-response.js" in "middlewares" folder.
function flattenArray(obj) {
return obj.map(e => flatten(e));
}
function flattenData(obj) {
return flatten(obj.data);
}
function flattenAttrs(obj) {
let attrs = {};
for (var key in obj.attributes) {
attrs[key] = flatten(obj.attributes[key]);
}
return {
id: obj.id,
...attrs
};
}
function flatten(obj) {
if(Array.isArray(obj)) {
return flattenArray(obj);
}
if(obj && obj.data) {
return flattenData(obj);
}
if(obj && obj.attributes) {
return flattenAttrs(obj);
}
for (var k in obj) {
if(typeof obj[k] == "object") {
obj[k] = flatten(obj[k]);
}
}
return obj;
}
async function respond(ctx, next) {
await next();
if (!ctx.url.startsWith('/api')) {
return;
}
ctx.response.body = flatten(ctx.response.body.data)
}
module.exports = () => respond;
And I called it in "config/middlewares.js"
module.exports = [
/* ... Strapi middlewares */
'global::flatten-response' // <- your middleware,
'strapi::favicon',
'strapi::public',
];

Location.requestForegroundPermissionsAsync is not a function

I just try to use expo-location and I found that error
Location.requestForegroundPermissionsAsync is not a function
this is my code
import * as Location from 'expo-location';
const setCurrentLocation = async() => {
let { status } = await Location.requestForegroundPermissionsAsync();
if (status !== 'granted') {
setErrorMsg('Permission to access location was denied');
return;
}
let location = await Location.getCurrentPositionAsync({});
setLocation(location);
if (errorMsg) {
setCheckText(errorMsg)
} else if (location) {
setCheckText(JSON.stringify(location))
}
}
To display the co-ordinates -
Initialize your state like this
const [location, setLocation] = React.useState(null);
Make your setCurrentLocation function like this
const setCurrentLocation = async () => {
let { status } = await Location.requestForegroundPermissionsAsync();
if (status !== 'granted') {
setErrorMsg('Permission to access location was denied');
return;
}
let location = await Location.getCurrentPositionAsync({});
setLocation(location);
};
Then your return part will look like this
return (
<View style={styles.container}>
{location ? <Text>latitude = {location.coords.latitude}</Text> : null}
{location ? <Text>longitude = {location.coords.longitude}</Text> : null}
</View>
);
Working Example

How to extract key and value from json in fetch method in React Native?

I'm new in React Native. I would like to extract a value from json with fetch to do a simple test to begin. But I don't understand, how to select a particular key from Json. Always, I have undefined return. I tried to modify my code with this post but it doesn't work. I tried to parse before but he didn't want because it's already an object.
This is my code:
checkLogin = () => {
const { name } = this.state;
const { surname } = this.state;
fetch('https://ffn.extranat.fr/webffn/_recherche.php?go=ind&idrch=' + name + '%20' + surname, {
method: 'GET',
}).then((response) => response.json())
.then((responseJson) => {
if (responseJson.ind == 'Individu non trouv\u00e9 !') {
alert("Id incorrect")
}
else {
alert("Id correct");
}
alert(JSON.stringify(responseJson.ind))
}).catch((error) => {
console.error(error);
});
}
This is my JSON format:
[{"iuf":"1366701","ind":"LEBRUN L\u00e9o (2000) H FRA - CN BEAUPREAU","sex":"#1e90ff","clb":"CN BEAUPREAU"}]
I know my request work because when I run this code alert(JSON.stringify(responseJson)).It return the entire json. So I don't know, how to resolve the undefined return.
Regards
Your json is an array, you either need to loop through it if there is multiple items inside, or just use responseJson[0] to read it. So if you want to read your json, your code would look like this :
const checkLogin = () => {
const { name } = this.state;
const { surname } = this.state;
fetch(
"https://ffn.extranat.fr/webffn/_recherche.php?go=ind&idrch=" +
name +
"%20" +
surname,
{
method: "GET"
}
)
.then(response => response.json())
.then(responseJson => {
// Since you have only one object inside your json, you can read the first item with 'responseJson[0]'.
if (responseJson[0].ind == "Individu non trouv\u00e9 !") {
alert("Id incorrect");
} else {
alert("Id correct");
}
alert(JSON.stringify(responseJson[0].ind));
// If you have multiple elements inside your responseJson,
// then here is a loop example :
// responseJson.forEach(item => {
// console.log('item ind = ', item.ind);
// });
})
.catch(error => {
console.error(error);
});
};
Use async await.
const checkLogin = async () => {
const { name } = this.state;
const { surname } = this.state;
const request = await fetch(
"https://ffn.extranat.fr/webffn/_recherche.php?go=ind&idrch=" +
name +
"%20" +
surname)
const response = await request.json();
console.log('result from server', response)
}

how to save image on local storage in angular 6

I am new in angular. I want to store image data on local storage.
localStorage.setItem("imgData", JSON.stringify(this.files));
this saving data but no value.
how do I save please help
I have something similar to your issue, it could help you.
renderPNG(fileName: string) {
let reader = new FileReader();
reader.addEventListener("load", () = > {
this.files = reader.result;
localStorage.setItem('imgData', JSON.stringify(this.files));
}, false);
this.files = JSON.parse(localStorage.getItem('imgData'));
if (!this.files) {
this.downloadService.downloadFileSystem(fileName, 'png')
.subscribe(response = > {
if (response && response.body.size > 0) {
reader.readAsDataURL(response.body);
}
});
}
}
use fetch
fetch('http://cors-anywhere.herokuapp.com/https://lorempixel.com/640/480/?60789', {
headers: {},
}).then((response) => {
return response.blob();
}).then((blob) => {
console.log(blob);
}).catch((e) => console.log(e));
and save the blob with
https://www.npmjs.com/package/fs-web
await fs.writeFile(this.dirPath + '/' + fileName, blob);
read file and get url
await fs.readString(this.dirPath + '/' + fileName).then(async (blob: Blob) => {
if (!!blob) {
if (blob.type === 'text/html' || blob.type === 'application/octet-stream') {
await fs.removeFile(this.dirPath + '/' + fileName);
} else {
const url = window.URL.createObjectURL(blob);
}
}
}).catch((err) => {
throw (err);
});
Reference used in library for IonicFramework https://www.npmjs.com/package/ion-media-cache

VueJs Axios Post FormData Parameters

We are using Vue in our frontend application, and for one of our REST service our backend server(using spring and java) expects to have the below data structure:
public class MAProductsUploadRequest
{
public List<MAProductUploadRequest> products;
}
public class MAProductUploadRequest {
public String productName;
public String productDescription;
public double productPrice;
public int productOrder;
public MultipartFile productImage=null;
public double cropX;
public double cropY;
public double cropWidth;
public double cropHeight;
public int categoryId;
}
And in our Vuejs application we tried to post the data as in the below code:
addProducts: function () {
console.log("Add Products Working. Total Product Count:"+this.excelProducts.length);
let header = {
headers: auth.getAuthHeader()
};
let formData = new FormData();
for (let i=0;i<this.excelProducts.length;i++ ) {
console.log("Starting loop:"+i);
var prod = this.excelProducts[i];
console.log("Product Before:"+prod);
if (document.getElementById('photo-image-'+i) !== null) {
if(document.getElementById('photo-image-'+i).files.length !== 0) {
console.log("Getting Image For Prod");
prod.productImage = document.getElementById('photo-image-'+i).files[0] ;
}
}
prod.cropX = this.cropProp.x;
prod.cropY = this.cropProp.y;
prod.cropWidth = this.cropProp.width;
prod.cropHeight = this.cropProp.height;
prod.rotate = this.cropProp.rotate;
console.log("Product After:"+prod);
formData.append("products[]",prod);
}
for (var pair of formData.entries()) {
console.log(pair[0]+ ', ' + pair[1]);
}
//console.log("Form Data:"+formData.products);
if (formData.products !== null) {
axios.post(`${API_URL}/company/uploadProducts`, formData, header).then((response) => {
logForDevelopment(response);
this.getProducts();
this.product = {
id: '',
name: '',
description: '',
price: '',
photo: '',
isEdit: false
};
this.excelProducts = [];
this.isPhotoChosen = false;
this.isPhotosChosen = [];
this.cropImg = '';
document.getElementById('photo-image').value = null;
this.isLoading = false;
}).catch((error) => {
this.isLoading = false;
if(error.response) {
logForDevelopment(error);
document.getElementById('photo-image').value = null;
if(error.response.status === 401 || error.response.status === 403) {
auth.afterInvalidToken('login');
}
}
})
} else {
console.log("Form Data Is Empty");
}
},
But when we use this code (even if the photo-image was null) the backend server returns HTTP 500 error. Because the products array seems null.
I wasn't able to figure it out where the problem may be in the Vuejs code?
EDIT: (I'VE also tried the below code but the still same result)
addProducts: function () {
console.log("Add Products Working. Total Product Count:"+this.excelProducts.length);
let header = {
headers: auth.getAuthHeader()
};
let formData = new FormData();
let prods = [];
for (let i=0;i<this.excelProducts.length;i++ ) {
console.log("Starting loop:"+i);
let prod = this.excelProducts[i];
let subFormData = new FormData();
subFormData.append("productName",prod.productName);
subFormData.append("productDescription",prod.productDescription);
subFormData.append("productPrice",prod.price);
subFormData.append("categoryId",prod.categoryId);
subFormData.append("cropX",this.cropProp.x);
subFormData.append("cropY",this.cropProp.y);
subFormData.append("cropWidth",this.cropProp.width);
subFormData.append("cropHeight",this.cropProp.height);
prods.push(subFormData);
if (document.getElementById('photo-image-'+i) !== null) {
if(document.getElementById('photo-image-'+i).files.length !== 0) {
console.log("Getting Image For Prod");
subFormData.productImage = document.getElementById('photo-image-'+i).files[0] ;
}
}
}
formData.append("products",prods);
console.log("Form Data:"+formData);
if (formData.products !== null) {
axios.post(`${API_URL}/company/uploadProducts`, formData, header).then((response) => {
logForDevelopment(response);
this.getProducts();
this.product = {
id: '',
name: '',
description: '',
price: '',
photo: '',
isEdit: false
};
this.excelProducts = [];
this.isPhotoChosen = false;
this.isPhotosChosen = [];
this.cropImg = '';
document.getElementById('photo-image').value = null;
this.isLoading = false;
}).catch((error) => {
this.isLoading = false;
if(error.response) {
logForDevelopment(error);
//document.getElementById('photo-image').value = null;
if(error.response.status === 401 || error.response.status === 403) {
auth.afterInvalidToken('login');
}
}
})
} else {
console.log("Form Data Is Empty");
}
},
What I'm actually trying to achive is, our below code works fine when sending single product info to our backend service, but I want to make it an array so send multiple products at once:
addProduct: function () {
let header = {
headers: auth.getAuthHeader()
};
let formData = new FormData();
formData.append('productName', this.product.name);
formData.append('productDescription', this.product.description === '' ? "" : this.product.description);
formData.append('productPrice', this.product.price);
formData.append('categoryId', this.product.categoryId);
if(document.getElementById('photo-image').files.length !== 0) {
formData.append('productImage', document.getElementById('photo-image').files[0]);
}
formData.append('cropX', this.cropProp.x);
formData.append('cropY', this.cropProp.y);
formData.append('cropWidth', this.cropProp.width);
formData.append('cropHeight', this.cropProp.height);
formData.append('rotate', this.cropProp.rotate);
console.log(formData);
axios.post(`${API_URL}/company/products`, formData, header).then((response) => {
logForDevelopment(response);
this.getProducts();
this.product = {
id: '',
name: '',
description: '',
price: '',
photo: '',
isEdit: false
};
this.isPhotoChosen = false;
this.cropImg = '';
document.getElementById('photo-image').value = null;
this.isLoading = false;
}).catch((error) => {
this.isLoading = false;
if(error.response) {
logForDevelopment(error);
document.getElementById('photo-image').value = null;
if(error.response.status === 401 || error.response.status === 403) {
auth.afterInvalidToken('login');
}
}
})
},
Does anyone have any idea about that?
You can also look at the screenshot of my application in below(I want to send all the items in screenshot , at once )
Your issue is probably il the formData.append("products[]",prod) method of your FormData class, try changing formData.append("products[]",prod) with formData.products.push(prod).
Furthermore in your axios call the payload should be formData.products if you API endpoint expects the products right?
Try axios.post(${API_URL}/company/uploadProducts, formData.products, header).
I do not see any syntax issue relative to Vue, hope this helps. (And of course check what is sent by XHR in devtools as suggested in the comments)