简体   繁体   中英

CORs Error only when trying to send a file to the API

I have a react app client that call a C# .net Core 2.2 API.

The API works fine with all other routes. (both testing in PostMan and running fine on functions in the application that uses AXIOS) I've created a route to upload files. This route works fine on PostMan, but when I call on a function in the application, the route returns an error:

Access to XMLHttpRequest at 'https://localhost:44356/upload/' 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.

My code:

Upload function:

    export const Upload = (ma, password, Files) => {
    const formData = new FormData();
    Files.forEach(file => {
        formData.append("files", file);
    });

    return new Promise((resolve, reject) => {
        axios.post(vars.servidor + 'upload/',
            formData, { headers: { "Content-Type": "multipart/form-data", "Access-Control-Allow-Origin": "*" } }
        ).then((response) => {
            resolve(response.data);
        }, (erro) => {
            reject(erro);
        });

    })
}

C# - Controllers.cs (the server route that receives the call)

 [HttpPost]
[Route("upload")]
public async Task<IActionResult> Upload(List<IFormFile> files)
{
    try
    {
        if (files.Count > 0)
        {
            await _fileService.SaveFiles(files);
            return Ok(await _fileService.GetFiles());
        }
        else
        {
            return StatusCode(204, "Erro ao enviar os arquivos!");
        }
    }
    catch (Exception e)
    {
        return StatusCode(500, e.Message);
    }
}

Startup.cs:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Latest);
    services.AddCors(options =>
    options.AddPolicy("CorsPolicy", builder => builder
    .AllowAnyOrigin()
    .AllowAnyMethod()
    .AllowAnyHeader()
    .AllowCredentials()
    )
    );

    services.AddScoped<IFileService, FileService>();
    services.AddSingleton((_) => Configuration);

}

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

    app.UseCors("CorsPolicy");
    //app.UseCors("LowCorsPolicy");

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

I found a solution: Changed the API call from axios to fetch. Works fine.

export const Upload = (ma, password, files) => {
return new Promise((resolve, reject) => {
    const data = new FormData();
    files.forEach(file => {
        console.log(file);
        var obj = dataURIToBlob(file);
        console.log(obj);

        data.append("files", obj);
    });

    const options = { method: 'POST', body: data };
    fetch(vars.servidor + 'upload/', options).then((response) => {
        resolve(response.json());
    }, (erro) => { reject(erro); });
})

}

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