I want the solution without using responseType in the get request because api is not accepting the response type.
responseType
has nothing to do with server. It tells Axios how to handle the expected response data. In this scenario you could pass responseType: "blob"
, which can be passed to URL.createObjectURL()
to create an URL that can be used as <img>
src
.
const url = 'https://api.bamboohr.com/api/gateway.php/tadigital/v1/employees/2223/photo/large';
axios.get(url, {
auth: {
username: 'xxxxxxxxxxxxxxxxx',
password: 'xxxxxxxxxxxxxxxxx',
},
responseType: 'blob',
}).then((resp) => {
const img = document.createElement('img');
img.src = URL.createObjectURL(resp.data);
img.alt = 'employee photo';
document.body.append(img);
});
const url = "data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9Ii0xMS41IC0xMC4yMzE3NCAyMyAyMC40NjM0OCI+CiAgPHRpdGxlPlJlYWN0IExvZ288L3RpdGxlPgogIDxjaXJjbGUgY3g9IjAiIGN5PSIwIiByPSIyLjA1IiBmaWxsPSIjNjFkYWZiIi8+CiAgPGcgc3Ryb2tlPSIjNjFkYWZiIiBzdHJva2Utd2lkdGg9IjEiIGZpbGw9Im5vbmUiPgogICAgPGVsbGlwc2Ugcng9IjExIiByeT0iNC4yIi8+CiAgICA8ZWxsaXBzZSByeD0iMTEiIHJ5PSI0LjIiIHRyYW5zZm9ybT0icm90YXRlKDYwKSIvPgogICAgPGVsbGlwc2Ugcng9IjExIiByeT0iNC4yIiB0cmFuc2Zvcm09InJvdGF0ZSgxMjApIi8+CiAgPC9nPgo8L3N2Zz4K";
axios.get(url, {
responseType: "blob",
}).then((resp) => {
const img = document.createElement("img");
img.src = URL.createObjectURL(resp.data);
img.alt = "React icon";
document.body.append(img);
}).catch((error) => {
console.log(error);
});
<script crossorigin src="https://unpkg.com/axios@1/dist/axios.js"></script>
Note that you should call URL.revokeObjectURL()
if you no longer need the URL.