admin管理员组

文章数量:1406312

I 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.

I 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.

Share Improve this question edited Jan 29, 2020 at 8:42 SRTechConnect asked Jan 29, 2020 at 6:03 SRTechConnectSRTechConnect 471 silver badge6 bronze badges 7
  • 192.00.00.60:8000/obj/e1b8c19e-fe8c-43af-800c-c9400c0e90/… what you are trying to do here – Prakash Karena Commented Jan 29, 2020 at 6:08
  • you have api / want to access your image url ??? – Prakash Karena Commented Jan 29, 2020 at 6: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 Commented Jan 29, 2020 at 6:11
  • It might help you: stackoverflow./questions/41846669/… – Sunil tc Commented Jan 29, 2020 at 6: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 Commented Jan 29, 2020 at 6:22
 |  Show 2 more ments

4 Answers 4

Reset to default 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}`} />
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 ing in response.

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);
 }
class Hello extends Component {
  state = {
    ulr: ''
  }
  ponentDidMount() {
      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.

本文标签: javascriptReactJS Axios Image RequestStack Overflow