1

enter image description hereI want make a request to API with headers having UserID:Pass

Example :

const config = {
  headers: {
    'X-RPC-DIRECTORY': 'main',
    'X-RPC-AUTHORIZATION': 'userid:pass'
  }
};

const res = await axios.get(`http://192.00.00.60:8000/obj/e1b8c19e-fe8c-43af-800c-c9400c0e90/abc.jpg`, config );

How can I render this? Using the same I can get the image in Postman, But I want to render this into the page.

SRTechConnect
  • 47
  • 1
  • 6
  • http://192.00.00.60:8000/obj/e1b8c19e-fe8c-43af-800c-c9400c0e90/abc.jpg what you are trying to do here – Prakash Karena Jan 29 '20 at 06:08
  • you have api / want to access your image url ??? – Prakash Karena Jan 29 '20 at 06:10
  • I want to render this jpg, but when I use this link directly, its showing this : {"message":"Couldn't create client credentials","errorReason":"MissingCredentials","error":"MissingCredentialException","path":"/obj/e1b8c19e-fe8c-43af-800c-30c9400c0e90/cutout.jpg","verb":"GET","status":401,"timestamp":1580278417361} – SRTechConnect Jan 29 '20 at 06:11
  • It might help you: https://stackoverflow.com/questions/41846669/download-an-image-using-axios-and-convert-it-to-base64 – Sunil tc Jan 29 '20 at 06:12
  • @PrakashKarena exactly, I have API and Image URL, I just want to access that image url from API, but it need authorization to access problem is that I don't know how. – SRTechConnect Jan 29 '20 at 06:22
  • what is role of your api from backend ? what you are doing when you are passing your image url to your api ?? – Prakash Karena Jan 29 '20 at 06:24
  • if you have problem with authentication then make sure you have your headers in backend side with your request – Prakash Karena Jan 29 '20 at 06:48

4 Answers4

4

1- Create useState to save your base64 data.

const [base64, setBase64] = useState();

2- Create useEffect or function to transform image from get request to base64.

useEffect(() => {
    axios
      .get(
        url,
        {
          responseType: "arraybuffer",
        }
      )
      .then((response) =>
        setBase64(Buffer.from(response.data, "binary").toString("base64"))
      );
  }, []);

3- Display the base64 data as image according to the syntax of the data URI scheme:

<img src={data:[<media type>][;charset=<character set>][;base64],<data>} />

example:

<img src={`data:image/jpeg;charset=utf-8;base64,${base64}`} />
Ala Hamadi
  • 251
  • 2
  • 7
0
axios({
        method:'get',
        url,
        auth: {
            username: 'xxxxxxxxxxxxx',
            password: 'xxxxxxxxxxxxx'
        }
    })
    .then((response) => {

        //From here you can pass the response to local variable(state) and store/show image. 

       this.setState({ imageURL : response.data.image }); // change this as per your response 

    })
    .catch((error) => {
        console.log(error);
    });

render(){
return(
  <React.Fragment>
   <img src={this.state.imageURL} alt="image" />
  </React.Fragment>
)
}

Make sure you have right method type, URL and data is coming in response.

Prakash Karena
  • 2,525
  • 1
  • 7
  • 16
Krina Soni
  • 870
  • 6
  • 14
  • the response I'm getting is not image url, instead its data, so, when I save that data as .jpg from postman, then its the image what i want, My question is that : How can I render that (data / response ) as image, because its not image url its data. (I've add the screenshot) – SRTechConnect Jan 29 '20 at 08:40
  • If the data is of base64, you can try this way. – Krina Soni Jan 29 '20 at 09:05
  • this is what i'm getting : - GET data:image/jpeg;base64,{props.getImage.firstImage} net::ERR_INVALID_URL – SRTechConnect Jan 29 '20 at 09:20
  • Why are you rendering through props? You have response coming from an API, you store that response in one local component's state and render through the same state. – Krina Soni Jan 29 '20 at 09:21
  • its because i'm using redux for state, props.getImage.firstImage contains : { data, status, statusText, headers, config, request} – SRTechConnect Jan 29 '20 at 09:32
0
class Hello extends Component {
  state = {
    ulr: ''
  }
  componentDidMount() {
      const config = {
      headers: {
      'X-RPC-DIRECTORY': 'main',
      'X-RPC-AUTHORIZATION': 'userid:pass'
      }
    };

  axios.get(`http://192.00.00.60:8000/obj/e1b8c19e-fe8c-43af-800c-c9400c0e90/abc.jpg`, config ).then((response) => {
    this.setState({ url: response.data })
  }).catch((error) => {
    console.log(error)
  })
  }
  render() {
    return (
      <>
        <img src={this.state.url} alt="#" />
      </>
    )
  }
}

export default Hello;

This should answer how to render the image after fetching the image from API. But what i think is something is wrong withe URL. i have few question:

  1. Is the back-end API hosted on our own system?
  2. Is the API publicly available because if it's not we cannot access it.
  3. Have you set ant other headers or params that needs to be sent along the request.
  4. I tried with postman also didn't get the image in response, it gave me error.
SRTechConnect
  • 47
  • 1
  • 6
  • Yes Back-end API hosted on local system, to access it we need header -> { 'X-RPC-AUTHORIZATION': 'userid:pass' } - but the problem is that the response is data not the image url, so that means when I save that data ( response ) as .jpg file from postman, then its working, So, my questions is that : How can I render that (data / response ) as image. – SRTechConnect Jan 29 '20 at 08:33
  • @SRTechConnect since i cant access the API as it's not publicly available can you past the response here thate you are getting. I am bit confused do you expect a resource URL to that image in API response or the content byte of the image? – Prasun Kumar Jan 29 '20 at 09:38
  • I think you might be receiving the content-byte data of image let me see the response then i can suggest a possible solution. – Prasun Kumar Jan 29 '20 at 09:40
  • @PrasanKumar - Please check added the screen shot of response – SRTechConnect Jan 29 '20 at 09:57
  • @SRTechConnect the problem is not on the react side. what i am seeing is you haven't stored the image in DB the right way. what i would suggest is not store images in DB at all. store them somewhere in a file system and store there relative path to the DB. in this way your DB remains light weight and you can send a resource URL of the image in the API response. and place that resource URL in the . depending upon what stack you have used on back-end there are many article that could help you with this to do it correctly. – Prasun Kumar Jan 30 '20 at 06:19
0

Got the Solution, as the response was content-type: blob so, what I did is to convert the blob to base64 from FileReader api and then display it.

const fileReaderInstance = new FileReader();
 fileReaderInstance.readAsDataURL(blob); 
 fileReaderInstance.onload = () => {
     base64data = fileReaderInstance.result;                
     console.log(base64data);
 }
SRTechConnect
  • 47
  • 1
  • 6