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.
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 coming in response.
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:
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);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.