I'm working on a web app using React for the frontend and ASP.NET Core for the backend.
This is code from my Startup.cs.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddCors(options =>
{
options.AddDefaultPolicy(builder =>
{
builder.WithOrigins("*").AllowAnyHeader().AllowAnyMethod();
});
});
}
This is my full API controller, which is working fine from Chrome when debugging with ISS in Visual Studio 2022.
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
namespace AsignacionesBackend.Controllers
{
[ApiController]
[Route("[controller]")]
public class ApiController : ControllerBase
{
private readonly ILogger<ApiController> _logger;
public ApiController(ILogger<ApiController> logger)
{
_logger = logger;
}
[Route("Login")]
public IActionResult Login()
{
JsonUser body = new JsonUser("hola", "buenas");
body.Token = "tokendeprueba";
JsonResult json = new JsonResult(body);
return json;
}
public class JsonUser
{
public string User { get; set; }
public string Pass { get; set; }
public string Token { get; set; }
public JsonUser(string user, string pass)
{
User = user;
Pass = pass;
}
}
}
}
This is the React code that is calling the API.
let result = fetch("https://localhost:5001/Api/Login");
result = await (await result).json;
console.log(result);
I'm receiving this error in the Chrome console when executing the React code:
Access to fetch at 'https://localhost:5001/Api/Login' from origin 'https://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
I'm new to both ASP.NET and React so any kind of help or tip is welcome. If you need more info I'll edit the question.
app.UseCors();afterapp.UseRoutinginConfiguremethod in startup?