0
votes

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

2

2 Answers

0
votes

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

-2
votes