Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
213 views
in Technique[技术] by (71.8m points)

reactjs - How to fix CORS error when fetching api data in my React application?

I recently uploaded my ASp.NET CORE React with Redux (and KendoUI React) project to my Azure hosting platform and now, I cannot access any data that is fetched from the API. I looked at the console and saw an error message of:

Access to fetch at 'https://login.microsoftonline.com/xxx-xxx-xxx-xxx-xxx/oauth2/authorize?client_id=xxx-xxx-xxx-xxx-xxx&redirect_uri=https%3A%2F%2Fmywebsite.azurewebsites.net%2Fsignin-oidc&response_type=id_token&scope=openid%20profile&response_mode=form_post&nonce=xxx.xxxstate=xxx-xxx-xxx-xxx-xxxxxx&x-client-SKU=ID_NET&x-client-ver=2.1.4.0' (redirected from 'https://mywebsite.azurewebsites.net/api/MyData/GetMyData?page=1&pageSize=20') from origin 'https://mywebsite.azurewebsites.net' has been blocked by CORS policy: 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.

I investigated the problem by searching the error message, I found a few posts but nothing concrete on exactly what to do in a react application that is best practice and also secure.

I added a header of Access-Control-Allow-Origin: * to my fetch but it didn't work. The other method I found was to use a proxy but the example was only supporting a local development environment.

Here is my fetch where you can see I added the Access-Control-Allow-Origin to the headers:

fetchData(dataState) {
    const queryStr = `${toDataSourceRequestString(dataState)}`;
    const hasGroups = dataState.group && dataState.group.length;
    const base_url = 'api/MyData/GetMyData';
    const init = { method: 'GET', accept: 'application/json', headers: "Access-Control-Allow-Origin: *" };

    fetch(`${base_url}?${queryStr}`, init)
        .then(response => response.json())
        .then(({ Data, total }) => {
                this.setState({
                    result: hasGroups ? translateDataSourceResultGroups(Data) : Data,
                    total,
                    dataState
                });
            }).catch(function (error) {
                console.log('Error: 
', error);
            });
};

Adding the header changed nothing and the error persists. I want to make sure I do this correctly, can anyone help me fix this error?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The Access-Control-Allow-Origin is a response header. It can only be set by the server. The server determines whether or not it accepts cross-site requests and in this case, the server says no. There's no way around it.

It seems you are trying to reach your Azure server but it redirects to the Microsoft login page. Make sure you can access the server without a redirect when making a request. Also make sure your JavaScript code is running on the same domain (I assume it is), otherwise configure CORS on the web server: https://docs.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-2.2


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...