在 React App 的 Active Directory 插件上获取 CORS 错误

Getting CORS error on Active Directory plugin for React App

我正在尝试将 Active Directory ADAL 插件集成到我的 Reactjs 应用程序中,但在获取结果时出现 CORS 错误。

我一直在关注 React ADAL package steps till I found a ,这对我帮助很大,但我在获取 Dynamics CRM 数据时仍然遇到 CORS 错误。

这是我的 MyComponent 组件的一部分:

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.

我在 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.

服务器错误:

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

有什么问题吗?提前致谢。

这是一个 CORS 问题。 CORS 代表跨源资源共享。 CORS 是您的浏览器实现的一项安全功能。

浏览器将看到某些 Javascript 请求已尝试向与浏览器当前所在域不同的域发起请求。

正因为如此,我们的浏览器会受到怀疑,这种行为无法更改,它已在每个浏览器中进行了硬编码。

在浏览器尝试发出请求之前,浏览器本身将向 api(也称为预检)发出初始请求。有点像:

"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?"

API 可以选择允许或禁止该请求。

在您的情况下,API 响应: "Hey browser, I agreed with you, this seems strange. You should only allow this request if your coming from the-other-domain.com"

API 响应然后返回到浏览器。然后浏览器返回 "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."

这就是您的应用程序中正在发生的事情。浏览器将检查是否有不同的域、子域或端口。如果这些事情有任何不同,CORS 就会启动。在你的情况下,你可能在 localhost:XXX 并且你正在向 https://myorg.api.crm.dynamics/api/

发出请求

请记住这是浏览器安全性。如果您在终端发出此请求表,例如 Postman 或 CURL。邮递员说: "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 和类似的应用程序没有 CORS 的东西,所以他们不关心。

这就是回答你问题的内容。