Skip to content Skip to sidebar Skip to footer

How To Get Image In Reactjs From Api?

I am fetching an image from nodejs API after verifying with JWT token. I am getting GET 200 ok response in browser Network header and picture can be seen in Preview, but I cannot u

Solution 1:

I was able to render images from a backend call in React using a pattern similar to this using: react hooks, axios, and URL.createObjectURL

I used the URL.createObjectURL(blob) method and used the axios configuration { responseType: 'blob' } to make sure the the data type would fit.

constImageComponent = (imageIds) => {
  const [images, setImages] = React.useState([])

  React.useEffect(() => {
    asyncfunctiongetImage (id) {
      let imageBlob
      try {
        imageBlob = (await axiosClient.get(`/api/image/${id}`, { responseType: 'blob' })).data
      } catch (err) {
        returnnull
      }
      returnURL.createObjectURL(imageBlob)
    }
    asyncfunctiongetImages () {
      const imageArray = []
      for (const id of imageIds) {
        imageArray.push(awaitgetImage(id))
      }
      setImages(imageArray)
    }

    getImages()
  }, [imageIds])

  return images.map((img, i) => {
    return<imgsrc={img}alt={`image-${i}`} key={i} />
  })
}

[Edit]: If your api is a protected route just make sure your axios http client is initialized with the token already

Solution 2:

This is my tried and tested method for fetching data:

componentDidMount(){
    fetch('https://www.yoursite.com/api/etc', {
      method: 'GET',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
      },
    })
    .then((response) => {
      return response.text();
    })
    .then((data) => {
      console.log( JSON.parse(data) )
      this.setState{( pic: JSON.parse(data) )}
    })
}

Then within your img

src={ this.state.pic }

Solution 3:

var myHeaders = newHeaders();
 myHeaders.append("response", "image/jpeg");
 myHeaders.append("psId", "");
 myHeaders.append("x-api-key", "Z7dwTzHQrklCh7bvSWqhNrDTPZiLblYS");
 myHeaders.append(
    "Authorization",
    "Bearer token"
 );

var raw = "";

var requestOptions = {
  method: "GET",
  headers: myHeaders,
  //body: raw,redirect: "follow",
};
let response = awaitfetch(
  "YourURL",
  requestOptions
)
.then((response) => response)
.then((result) => result)
.catch((error) =>console.log("error", error));

 res = await response.blob();

Then in image tag in your html or jsx file you can do it as follows:

<imgsrc={window.webkitURL.createObjectURL(res)} />

Solution 4:

I have found the answer. Here it is:

Working with the Fetch API - Google docs

Post a Comment for "How To Get Image In Reactjs From Api?"