How to access user's profile photo from Microsoft graph API and display React application?

Viewed 1423

I am trying to access the user's profile picture using Microsoft's Graph API. The following is my code to fetch the profile image :

export async function getprofilePhoto() {
  const accessToken = await getToken(loginRequest);
  const headers = new Headers();
  const bearer = `Bearer ${accessToken}`;
  headers.append("Authorization", bearer);

  const options = {
    method: "GET",
    headers: headers,
  };

  return fetch(graphConfig.graphMePhotoEndpoint, options)
    .then((response) => {
      if (response != null && response.ok) {response.blob().then((data) => {
          if (data !== null) {
            window.URL = window.URL || window.webkitURL;
            return window.URL.createObjectURL(data);
          }
        });
      } else {
        throw new Error("Profile image not found");
      }
    })
    .catch((error) => {
      throw new Error("Profile image not found");
    });
}

In my react component I pass on the returned data from the above function but it never renders the image. The code for my component looks like:

<Avatar
 alt={name}
 src={profileImage}
 className={classes.avatarMain}
 />

The profileImage is the returned data from getprofilePhoto() method. I can also see a request in network tab to https://graph.microsoft.com/v1.0/me/photo/$value with success response with image but it never shows up in my component.

Can someone help me figure out what am I doing wrong?

enter image description here

1 Answers

The problem was I had send one more header(key/value) which is "Content-Type", "image/jpeg" and code started working

Related