How to display an image that required bearer token to access it in react

Viewed 6245

I'm trying to find a way to display the image in my react app. The image I need requires a bearer token, in other words When I access this image, I need to pass a header with the bearer token. I'm moving from react-native to react, so in react-native, I can directly give header in Image component, but it seems like I can't pass header in img tag which is html tag. So my question is how to display an image that required bearer token to access it in react.

2 Answers

In case you are using axios don't forget to add the 'responseType', in other case it doesn't work.

axios
  .get(endpoint, {
    headers: { Authorization: 'xxxxxxxxxxxx' },
    responseType: "arraybuffer",
  })
  .then((response: any) => {
    let data = `data:${
      response.headers["content-type"]
    };base64,${new Buffer(response.data, "binary").toString("base64")}`;

use the image base source

constructor(props) {
   super(props);
   this.state = {
      imgSrc: '',
   };
}
componentDidMount() {
    fetch('http://localhost:8181/images/appliance-OTHER.svg', {
         method: "GET",
         headers: { Authorization: 'Bearer eyJhbGciOiJIU' }
    }).then((response) => {
        const data = `data:${response.headers['content-type']};base64,${new Buffer(response.data).toString('base64')}`;
            this.setState({ imgSrc: data });
    });
}
render() {
  const { imgSrc } = this.state;
  return (
     <img src={imgSrc} alt="love is gone" />
  )
}
Related