Getting CORS error on Active Directory plugin for React App

I am trying to integrate Active Directory ADAL plugin within my Reactjs app but I am getting CORS error when fetching results.

I was following React ADAL package steps till I found a SO question which helped me a lot, but still I am getting a CORS error while fetching Dynamics CRM data.

This is part of my MyComponent component:

import React, { Component } from 'react';
import { adalApiFetch } from '../../../adalConfig';

class MyComponent extends Component {
    constructor(props) {
        super(props);

        this.state = { APIResponse: '' };
        this.getLeads = this.getLeads.bind(this);
    }

    componentDidMount() {
        this.getLeads();
    }

    getLeads() {
        let result;

        /*(async () => {
            let response = await fetch('https://myorg.api.crm.dynamics.com/api/data/v9.1/leads');
            let data = await response.json();

            console.log(data);
        })();
        fetch('https://myorg.api.crm.dynamics/api/data/v9.1/leads')
        .then(response => response.json())
        .then(data => {
            console.log(data);
        })
        .catch(error => console.error('SERVER ERROR:', error));*/
        const options = {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json'
            },
            mode: 'cors'
        };

        adalApiFetch(fetch, 'https://myorg.api.crm.dynamics/api/', options)
        .then(response => response.json())
        .then(data => {
            this.setState(Object.assign(this.state, { APIResponse: data }));
            console.log(data); 
        }).catch(error => console.error('SERVER ERROR:', error));

    }

    render() {
        return (
            <div>
                <h2>My Component</h2>
            </div>
        );
    }
}

export default MyComponent;

I kept the comments in case you suggest me to make the fetch request with the ES7 approach instead of the ES5/6.

I am getting this error on the DevTools:

Access to fetch at 'https://login.microsoftonline.com//oauth2/authorize?client_id=0&response_mode=form_post&response_type=code+id_token&scope=openid+profile&state=OpenIdConnect.AuthenticationProperties%-SNnykyS3kfmCGv0ar3tRJMn0XvPSwEAAAABBBBBCS5yZWRpcmVgdClodHRwczovL25ld2NvMi5hcGkuY3JtMi5keW5hbWljcy5jb20vYXBpLw%26RedirectTo%3dhttps%253a%252f%252fmyorg.api.crm2.dynamics.com%252f&nonce=636848908126477531.RGFhOTkxMzQtqDRlYy00Nzk3LThkZDgtZjk5MjA5MDM3Nzk5MWQyMTE4OWQtODNjMy00YzhhLTk2YjMtMzY4MmQ0MzFkZjU5&redirect_uri=https%3a%2f%2fcloudredirector.crm2.dynamics.com%3a443%2fG%2fAuthRedirect%2fIndex.aspx&max_age=86400' (redirected from 'https://myorg.api.crm2.dynamics.com/api/') from origin 'null' 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. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

Server error:

index.js:1446 SERVER ERROR: TypeError: Failed to fetch

Any ideas on what is wrong here? Thanks in advance.

1 answer

  • answered 2019-02-06 10:14 henrik123

    This is a CORS issue. CORS stands for Cross Origin Resource Sharing. CORS is a security feature implemented by your browsers.

    The browser is going to see that some Javascript request has tried to initiate a request to a different domain than what the browsers is currently at.

    Because of this our browser is going to be suspicious, this behavior can not be changed, its hard coded in every browser.

    Before the browser attempts to make the request the browser itself is going to do a initial request to the api(aka preflight). Kinda like:

    "Hey API, I'm trying to make a request over do you. The request is coming from a website at some-domain.com, it seems strange, what do you think?"

    The API has the option to either allow or disallow the request.

    In your case, the API response: "Hey browser, I agreed with you, this seems strange. You should only allow this request if your coming from the-other-domain.com"

    The API response then goes back to the browser. And then the browser says back "Hey you know what, the server says that you can not make a request over to them at while your at some-domain.com. Sorry Javascript code we're not allowed to do that."

    That is what is happening in your application now. The browser is going to check if there's a different domain, subdomain or port. If any of these things are different, the CORS kicks in. In your case your probably at localhost:XXX and you're making a request to https://myorg.api.crm.dynamics/api/

    A thing to keep in mind is this is a Browser security. If you make this request form e.g Postman or CURL at the Terminal. Postman says: "You know what, I don't care if you make a request to a different API. Im not the browser and you can do anything you want."

    Postman and similar applications don't have CORS stuff so they don't care.

    That's whats going on to answer your question.