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); });
})
}