Shady Hakim
Shady Hakim

Reputation: 415

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

Upvotes: 0

Views: 6792

Answers (2)

Shady Hakim
Shady Hakim

Reputation: 415

After many hours of searching i found this chrome extension that solve the problem https://chrome.google.com/webstore/detail/allow-cors-access-control/lhobafahddgcelffkeicbaginigeejlf

Upvotes: -1

Burak Gavas
Burak Gavas

Reputation: 1354

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

Upvotes: 2

Related Questions