How to GET image in reactjs from api?

本小妞迷上赌 提交于 2020-06-26 07:35:12

问题


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 use it in my app.

I am surely doing something wrong. Please let me know the proper way to display image from API. On my backend nodejs, I am using res.sendFile to send the file.

class Card extends Component {
 constructor({props, pic, token}) {
super(props, pic, token);
this.state = { 
  pic: pic,
};

urlFetch(data) {
 fetch(data, { 
 headers: new Headers({
 'authorization': `Bearer ${this.props.token}`, 
 'Content-Type': 'application/json'
 })
})
.then(response => {
 if (response.statusText === 'OK') {
  return data   // OR return response.url
  }
 })
}

render() {
const { pic } = this.state;

 return (
        <div>
          <img style={{width: 175, height: 175}} className='tc br3' alt='none' src={ this.urlFetch(pic) } />
        </div>
       );
      }
     }

回答1:


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 }



回答2:


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.

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

  React.useEffect(() => {
    async function getImage (id) {
      let imageBlob
      try {
        imageBlob = (await axiosClient.get(`/api/image/${id}`, { responseType: 'blob' })).data
      } catch (err) {
        return null
      }
      return URL.createObjectURL(imageBlob)
    }
    async function getImages () {
      const imageArray = []
      for (const id of imageIds) {
        imageArray.push(await getImage(id))
      }
      setImages(imageArray)
    }

    getImages()
  }, [imageIds])

  return images.map((img, i) => {
    return <img src={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




回答3:


 var myHeaders = new Headers();
 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 = await fetch(
  "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:

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



回答4:


I have found the answer. Here it is:

Working with the Fetch API - Google docs



来源:https://stackoverflow.com/questions/50344055/how-to-get-image-in-reactjs-from-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!