Cors error in application dotnet core + React web app

Asked

Viewed 74 times

1

I have an application problem that when I send files via POST and the image is larger in Mb Cors error occurs, images of a few kb work normally. Dotnet core api In the api I already added Cors and added permissions in configure services:

services.AddCors(options => options.AddPolicy("CorsPolicy", builder => builder
          .AllowAnyOrigin()
          .AllowAnyMethod()
          .AllowAnyHeader()
          //.AllowCredentials())
          ));

and no configure:

 app.UseCors("CorsPolicy");

Testing via Postman, regardless of image size, no error occurs.

With small image and no error occurs: response sem erro com imagem pequena

With large image and error occurs: Response com erro em arquivo maior

React Code with Axios

api
  .post(`anuncio/${anuncio.idImovel}/imagem`, data, {
    mode: 'cors',
    headers: {
      'content-type': 'multipart/form-data',
      'Access-Control-Allow-Origin':'*',
      authorization: `bearer ${getToken()}`,
    },
    onUploadProgress: (e) => {
      const progress = parseInt(Math.round((e.loaded * 100) / e.total));
      this.updateFile(uploadedFile.id, {
        progress: progress,
      });
    },
  })
  .then((response) => {
    this.updateFile(uploadedFile.id, {
      uploaded: true,
      imagemPrincipal: !principal && index === 0,
      id: response.data.id.toString(),
      href: response.data.link.href,
    });
  })
  .catch(() => {
    this.updateFile(uploadedFile.id, {
      error: true,
      uploaded: true,
    });
  });

};

Environmental data Linux server hosted on AWS. We use NGINX on the frontend. Dotnet core (Kestrel on linux). The upload is done to the S3 of aws (I’ve already set the Cors policies in Bucket).

  • It doesn’t seem q to be a Cors problem. Anyway, you have already activated all exceptions (same handled) in ide?

  • Another point, n related to the question, but if you don’t do anything with the image (just get it in your api and send it to aws) you can upload it right there. For this you can generate a specific temporary token for a single upload.

  • Hi @tvdias thanks for the return, your tip is an excellent plan B, it seems that whoever is limiting this is the NGINX, it does not show to be taking the limit setting client_max_body_size XMB. We’ll test it with the Apache to see if it works.

  • I will activate the exceptions in production, had not done it.

1 answer

0

I believe it is inverted, in the "Configureservices" you add the " services.Addcors();" and in the "Configure" app.Usecors(options => options.Allowanyorigin(). Allowanymethod(). Allowanyheader());

Full example:

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

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<MeuDbContext>(options =>
                   options.UseSqlServer(
                   Configuration.GetConnectionString("DefaultConnection")));

       
            services.AddCors();
            services.AddSpaStaticFiles(diretorio =>
            {
                diretorio.RootPath = "NomeDoSeuApp";
            });

            services.AddControllers().AddJsonOptions(opcoes =>
            {
                opcoes.JsonSerializerOptions.IgnoreNullValues = true;
            }).AddNewtonsoftJson(opcoes => {
                opcoes.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
            });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseCors(opcoes => opcoes.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());


            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();

            app.UseStaticFiles();
            app.UseSpaStaticFiles();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });

            app.UseSpa(spa =>
            {
                spa.Options.SourcePath = Path.Combine(Directory.GetCurrentDirectory(), "NomeDoSeuApp");
                if (env.IsDevelopment())
                {
                    spa.UseProxyToSpaDevelopmentServer($"http://localhost:4200/");
                }


            });
        }
    }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.