Search code examples
javascriptangularjsmicrosoft-graph-apihttprequestonedrive

Microsoft Graph CORS preflight error on file download


Context:
I am trying to download files into a buffer for AngularJS application in order to forward the file to the backend for storing on the server (backend is not under my control) therefore I need to get file data into Blob which then gets uploaded my our own servers.

Issue:
Microsoft graph gives me their recommended @microsoft.graph.downloadUrl property in the JSON file which retrieves a list of all files in the currently selected folder. As I use it to download the file itself I get hit with Access to XMLHttpRequest at [the URL from @microsft.graph.downloadUrl] from origin 'http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

My code:

const req = {
  method: "GET",
  url: file.item.downloadLink, // @microsoft.graph.downloadUrl
  headers: {
    Authorization: `Bearer ${this.token}`
  },
  eventHandlers: getEventUploadEvenHandlers(file), // update download progress bar
  responseType: "blob"
};
const ret = await this.$http(req);

My research:
I looked through this article from 5 years ago: https://github.com/microsoftgraph/microsoft-graph-docs/issues/43
I read the entire article about CORS and files here: https://learn.microsoft.com/en-us/onedrive/developer/rest-api/concepts/working-with-cors?view=odsp-graph-online
Of course, I have read the documentation: https://learn.microsoft.com/en-us/graph/api/driveitem-get-content?view=graph-rest-1.0&tabs=http

Nothing has given me an answer to why would the issue persist
If you have any experience with this issue or notice something you think I missed I would be very grateful.

Thank you for any help


Solution

  • So basically my whole approach was wrong.
    I deduced from other cloud services that Microsoft Graph would return JSON with data of the file.
    MICROSOFT RETURNS THE FILE ITSELF
    Therefore fetch or a very simple request without any headers required is enough to get the file and then with .blob() or responseType: 'blob' you get a blob from the response.

    (await fetch([@microsoft.graph.downloadUrl])).blob() // returns Blob promise