简体   繁体   中英

react Access to XMLHttpRequest has been blocked by CORS policy No 'Access-Control-Allow-Origin' header is present on the requested resource

i am trying to access data from an api but i got this error

Access to XMLHttpRequest at ' http://example.com/api/login ' from origin ' http://localhost:3000 ' 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.

this is my code

return axios.post('http://example.com/api/login', { username: username, password: password }).then(response => {
        console.log('response', response);

        if (response.status === 400 || response.status === 500)
            throw response.data;
        return response.data;
    }).catch(err => {
        console.log('err', err);

        throw err[1];
    });

Backend built with asp.net

Thank you

This issue is about your server. Your server does not allow requests which come from different domains. In your case, http://example.com/api/login and http://localhost:3000 are in different domains. You can allow any domain you want in your asp.net code. The following code might be useful for you:

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";

    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddCors(options =>
        {
            options.AddPolicy(MyAllowSpecificOrigins,
            builder =>
            {
                builder.WithOrigins("http://example.com",
                                    "http://www.contoso.com");
            });
        });

        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseHsts();
        }

        app.UseCors(MyAllowSpecificOrigins); 

        app.UseHttpsRedirection();
        app.UseMvc();
    }
}

For more, you can navigate here

经过数小时的搜索,我发现这个 chrome 扩展可以解决这个问题https://chrome.google.com/webstore/detail/allow-cors-access-control/lhobafahddgcelffkeicbaginigeejlf

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM