Search code examples
javascriptreactjssharepointcorsmicrosoft-graph-files

How to enable CORS in Sharepoint Online


I am trying to implement share point file browser in my react application. Using microsoft/file-browser for this ans code as follows. But getting the xxx... from origin 'http://localhost:3000' has been blocked by CORS policy

Any ideas how can I enable CORS for this

import * as React from "react";

import { GraphFileBrowser } from '@microsoft/file-browser';

class App extends React.Component {


  getAuthenticationToken() {
    return new Promise<string>(resolve => {
      resolve(
        "VALID TOKEN"
      );
    });
  }

  render() {
    return (
      <GraphFileBrowser
        getAuthenticationToken={this.getAuthenticationToken}
        onSuccess={(selectedKeys: any[]) => console.log(selectedKeys)}
        onCancel={(err: Error) => console.log(err.message)}
        endpoint='https://XXX.sharepoint.com'

      />
    );
  }
}

export default App;

Solution

  • As far as i can tell the CORS error does not occur because of SharePoint, but because of your Browser. The problem here is that you are trying to load resources from xxx.sharepoint.com to localhost (which per default is never added as accepted in CORS)

    So one solution would be to use a CORS-unsensitive browser. This could be the following:

    cd "C:\Program Files (x86)\Google\Chrome\Application"
    chrome.exe --disable-web-security --user-data-dir="C:\tmp"
    

    This snippet starts your Google Chrome without "Web Security" (includes CORS) using the User Data Directory "C:\tmp".

    Remember that this workaround only works for development. In production you should not use localhost...

    https://www.thepolyglotdeveloper.com/2014/08/bypass-cors-errors-testing-apis-locally/