image is not loading and being blocked by CORB - reactjs

I am getting a data with an image link and I want to show those images by using the link in my img tag. I have disabled CORS on my chrome and I am receiving the data successfully but when I try to render the image it gives me an error "Cross-Origin Read Blocking (CORB) blocked cross-origin response https://commons.wikimedia.org/wiki/File:A_Conversation_With_Oscar_Wilde_-_London_-_240404.jpg with MIME type text/html. See https://www.chromestatus.com/feature/5629709824032768 for more details"
Can you please help on how can I bypass this. I am using axios for to make the fetch request and React to render the image.
async function getData(location) {
try {
// Make API call to get coordinates of location
const geonameResponse = await axios.get(`https://api.opentripmap.com/0.1/en/places/geoname?name=${location}&apikey=${API_KEY}`)
//console.log(geonameResponse)
// Make API call to get features within 1000 meter radius of location
const radiusResponse = await axios.get(
`https://api.opentripmap.com/0.1/en/places/radius?radius=1000&lon=${geonameResponse.data.lon}&lat=${geonameResponse.data.lat}&limit=10&apikey=${API_KEY}`)
//console.log(radiusResponse)
// Make API call for each feature to get more detailed information
// Make API call for each feature to get more detailed information
const xidResponses = await Promise.all(
radiusResponse.data.features.map(async (item) => {
return new Promise((resolve) => {
setTimeout(async () => {
resolve(await axios.get(
`https://api.opentripmap.com/0.1/en/places/xid/${item.properties.xid}?apikey=${API_KEY}`
));
}, 2000);
});
})
);
// Set data to array of xidResponses
setData(xidResponses);
} catch (error) {
console.error(error);
}
}

Related

Axios API call returns a 404 on page render, but still returns api objects in terminal

I am using axios to make an api call to an api found on Apihub for a next JS app.
here is the code for the function to make the call to provide a list of property JSON objects.
export const baseUrl = "https://zillow56.p.rapidapi.com"
export const fetchApiListsingsCustom = async (url) => {
const { data } = await axios.get((url), {
method: 'GET',
headers: {
'X-RapidAPI-Key': '328713ab01msh862a3ad609011efp17e6b4jsn0e7112d5ee9a',
'X-RapidAPI-Host': 'zillow56.p.rapidapi.com'
}
});
data.then((res) => {
console.log(res);
})
.catch((error) => {
console.error(error);
});
return data.json();
}
When rendering the page I'm attempting to inject the response's data to dynamically create a list of apartment listings.
I'm trying to use getServerSideProps so that the data is already available by the time a user requests the page. After fetching the data, I want to also print them in the terminal to validate it's success.
export default function Home({ propertiesCustomdata })
export async function getServerSideProps() {
const propertiesCustom = await fetchApiListsingsCustom(`${baseUrl}`)
const propertiesCustomdata = propertiesCustom.json()
return {
props: {
propertiesCustomdata
}
}
}
The problem is, I seem to be getting a 404 error from the axios call, before the page gets a chance to load. When I access this I get a 404 error but I also manage to receive some contents of the call the API was to make.
My apologies if this is unclear, but this is all I know to report on this so far.
Studying async and await, fetch, and axios. Very confusing.

Firebase Storage async request with "listAll" method. React

I'm getting an image from a user and storing it with in Cloud Storage through Firebase. The storing works fine.
Right after that I'm requesting all images from the storage to display them, but I got the response without the last submit. So I need to refresh the page, then useEffect make one more request and everything works.
UPD. Here's the the complete logic:
This function is uploading image to the storage:
const uploadImage = async (image,imageName) => {
if (image == null) return;
const imageRef = ref(storage,`images/${imageName}`);
try {
uploadBytes(imageRef, image);
} catch (err) {
alert(`${err}`)
}
}
This function does request to firestore, but doesn't return last uploaded image every time, just randomly. sometimes it does, usually not :
const getImages = async () => {
try {
const imagesListData = await listAll(imagesListRef);
setImagesList([]);
imagesListData.items.forEach(item => {
getDownloadURL(item).then(url => setImagesList(prev => [...prev,url]));
})
} catch(err){
alert(err.message);
}
}
after refreshing the page, useEffect does the job :
useEffect(() => {
getImages();
},[])
As I said above sometimes it works as I expected from the first try without me changing the code(which is the most confusing),most of the times I need to refresh the page to get the last image.
p.s. list() instead listAll() give same results

Is there away to make a popup do a request to display extra information

I am trying to make an information board that when user press for more information, it will do a get /:id to the backend where it will grab the data and display it in the popup
You can do something like:
const onClickHandler= async () => {
const res = await fetch(endpoint);
const data = await res.json();
setData(data)
}
But using try catch and the rest of things to validate a successful req.

React fetch local json file for testing does not work

I'm trying to fetch a .json file from local, and
I get response 200 but with a body response of HTML: "You need to enable JavaScript to run this app."
I have javascript enabled of course.
I don't want to import the file to simulate the real fetch.
How does local fetch work in react? How do I know if the fetch route is right? It doesn't give any useful error hint.
useEffect(() => {
const getData = async () => {
const dataFromLocal = await fetchData();
console.log('dataFromLocal', dataFromLocal);
}
getData();
}, [])
const fetchData = async () => {
const response = await fetch('data.json');
const data = await response.json();
return data;
}
I found how it works:
const response = await fetch('data.json',
{headers:
{'Content-Type': 'application/json','Accept': 'application/json'}
});
just add this headers object to the fetch method and it works
There are only two possibilities based on the code you've shown:
Your server is responding with the contents of an HTML resource (likely index.html) as the response to the request for data.json, or
data.json looks like this, the JSON string you provided:
"You need to enable JavaScript to run this app."
Is data.json in your project's ./public folder?

not able to fetch api response

I have written an API where I am generating data in JSON format.
Now I am calling same API on react frontend. If response is generated we will display a success page else we will divert to same page. So I have written these code when I submit user id and password on submit event validateLogin API has been called, but I am not able to execute body of API response.
onSubmit = async => {
const { user_mail, user_pass1 } = this.state
const payload = { user_mail, user_pass1}
api.validateLogin(payload).then((res) =>{
alert('Success');
})
.catch((err) =>{
alert('Failed');
})
}
Here nothing is executing. Can you please help me to execute response body?

Resources