How to fix CORS error when fetching api data in my

2019-09-21 21:57发布

问题:

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: \n', 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?

回答1:

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



回答2:

Use https://cors-anywhere.herokuapp.com append this to your api

eg: https://cors-anywhere.herokuapp.com/user/list

This is a public proxy and there is no control over who sees the data, do not overload the proxy server. best to implement your own proxy if its impossible to alter the azure api.