What's the best way to import a file from OneDrive to an Angular app using Typescript?

I am currently working on an Angular application that utilizes OneDrive/Sharepoint for file storage. Authentication is functioning properly, and I can successfully save files. However, I am encountering an issue when attempting to download a file created and stored using the Angular HttpClient.

The code snippet in question is as follows:

export class MicrosoftService {

   private graphUri = 'https://graph.microsoft.com/v1.0';

   constructor(private http: HttpClient) {}

   public loadFile(id: string, next: (saved: string) => void): void {
  
        this.http.get(this.graphUri + '/me/drive/items/' + id + '/content', { headers: this.getOAuthHeader() })
             .subscribe((response: any) => {
                console.log(response.toString());
                next(response.toString());
            });
    }

    getOAuthHeader(): HttpHeaders {
       // code generating OAuth headers, functions correctly
    }

}

It's clear that further processing of the response will be needed once it can be received.

The issue arises when the GET request is initiated, leading to a correct request to Graph, which then results in a 302 redirect to

https://foozlecorporation-my.sharepoint.com/drive/path/_layouts/15/download.aspx?UniqueId=a-bunch-of-url-params
. While downloading content from a REST client works smoothly, attempts to do so in the browser (currently Safari) trigger a
Browser cannot load [...url...] due to access control checks
error upon encountering the redirect.

Although my application headers include Access-Control-Allow-Origin: *, allowing usage of Graph initially, the Sharepoint response does not contain Access-Control-Allow-Origin. What additional steps should I take?

Answer №1

Issue

It has been mentioned that the endpoint

https://foozlecorporation-my.sharepoint.com/drive/path/_layouts/15/download.aspx?UniqueId=a-bunch-of-url-params
does not provide any Access-Control-Allow-Origin header.

When a CORS request is sent from origin A to an endpoint on origin B (https://graph.microsoft.com) and the response permits origin A but results in a cross-origin redirect to an endpoint on origin C (

https://foozlecorporation-my.sharepoint.com
), the browser performs a new CORS access-control check for origin A on origin C. If origin C is not set up for CORS or does not allow origin A, the overall CORS request will fail.

Potential Resolution

One possible solution is to make the request to https://graph.microsoft.com from your backend rather than from your frontend. This approach bypasses the CORS issue since CORS does not apply to non-browser user agents.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The undefined request body in Node.js is causing some confusion

I am currently working on a client-side Angular application that sends POST requests to a Node.js server. order(market: string, price: string, side: string, size: string): Observable<any> { var payload = { market: market, order: { price: pri ...

Tips for customizing the appearance of a mat-select chosen item?

Is there a way to modify the color of the selected option text in a mat-select component within an Angular 15 project? .html <mat-form-field> <mat-label>From</mat-label> <mat-select panelClass="mat-select-red"> ...

Minimize the quantity of data points displayed along the X-axis in a highcharts graph

After making an API call, I received data for a Highcharts graph consisting of an array of datetimes (in milliseconds) and corresponding values (yAxis). The data is fetched every 15 minutes and displayed on a mobile device. When viewing the data monthly, ...

Encountering issues when trying to combine Sequelize with TypeScript

As I attempted to transition my NodeJs application to TypeScript, I encountered issues with Sequelize. Upon attempting to implement the code from a website, an error occurred: This expression is not constructable. Type 'typeof import("/home/de ...

Forwarding from a user interface element in Next.JS

I am currently working on a project utilizing Next.js 13, and I have encountered a situation where I need to invoke a client-side component from a server-side page. The specific component in question is the DeleteAddressAlertDialog which interacts with my ...

Error: Unexpected token 'export' in NextJS Syntax

A situation has arisen where a library that was functioning perfectly in an app utilizing react-create-app is now needed for use in NextJS (using npx create-next-app --ts). However, upon attempting to integrate the library, an error was encountered: erro ...

Utilize NestJS to retrieve information from an observable gRPC service

One of the challenges I am facing is using gRPC service to facilitate communication between my microservices. Specifically, when receiving a response from the Grpc service, I need to apply some modifications and additional functionality before returning a ...

Guide on importing videojs-offset library

I am working on a component that utilizes video.js and HLS streaming in Angular. The component code is as follows: import { Component, ElementRef, AfterViewInit, ViewChild, Input, EventEmitter, Output } from '@angular/core'; import ...

Tips for effectively typing a collection of React wrappers in TypeScript

I encountered a situation in my team's application where we need the ability to dynamically compose component wrappers (HOCs) without prior knowledge of all the wrapper interfaces. This is mostly needed for swapping out context providers when renderin ...

Stop pages from breaking in jsPDF due to text overflow

Currently, I am utilizing the jsPDF and html2canvas libraries to generate a PDF file from HTML content. An issue that I am facing is dealing with dynamic content where it is challenging to determine when each page ends. I have implemented a function to c ...

How to Disable Back Button During Angular 2 REST API Requests?

Within my Angular 2 application, a REST API call is made to process a functional flow and receive a response from the server. During this process, I want to prevent users from navigating using the browser's Back button. To achieve this, I have implem ...

The interface IJobDetails cannot be assigned to type null

https://i.sstatic.net/cVVSs.png In the code snippet below, I have created an interface called ClientState1. Now, I am attempting to define a constant named descriptionJobDetails with the type ClientState1, specifically for IJobDetails. However, I am encou ...

What is the proper way to validate a property name against its corresponding value?

Here is the structure of my User class: export class User { public id: number; //Basic information public email: string; public firstName: string; public lastName: string; //Permissions public canHangSocks: boolean; p ...

Struggling to integrate D3.js with React using the useRef hook. Any suggestions on the proper approach?

I'm currently working on creating a line chart using d3.js and integrating it into React as a functional component with hooks. My approach involved utilizing useRef to initialize the elements as null and then setting them in the JSX. However, I encou ...

What is the reason behind the restriction on using 'this' on the left side of an assignment?

Within the component class, I've been working on this: export class myapp { detail; myarr = ['me', 'myself', 'i']; title = this.myarr[0]; this.detail = this.title ; //error } I'm curious why `this.detail` ...

Tips for concealing error messages in Angular 7 when an input field is in focus

Is there a way to hide the custom validation message div when the input field is in focus? I'm looking for a solution to this issue. <div class="form-group"> <label class="col-sm-4 control-label">Password</label> <div class ...

Why is my ASP.NET Core Crud request failing with incorrect method matching?

I am facing an issue with the third method in my Angular ASP.NET Core Controller. The first two methods work fine, but the GetBookItemsByTitle does not seem to be firing correctly. As I am still learning, I believe my mistake here is obvious. /// <summ ...

What is the technique for highlighting the exact data point on the XY am4chart when it is clicked?

I have been searching high and low for a solution to my problem but haven't had any luck. I am working with a traditional XY am4chart that has hundreds of data points in the line series. What I want is for the chart to display a vertical line (or some ...

Trouble triggering hidden radio button in Angular 9 when clicked

I have implemented radio buttons within a div with the following CSS styles (to enable selection by clicking on the div): .plans-list { display: flex; justify-content: center; margin: 2rem 0; .plan { display: flex; margin: 0 0.5rem; p ...

"Adjusting the position of an Ionic Menu on-the-fly

As I strive to update the Ionic 3 Menu side dynamically when the user changes the language, a challenge arises for RTL languages where the menu needs to be on the right instead of the default left. To tackle this issue, I have subscribed to the TranslateS ...