skip to Main Content

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.

2

Answers


  1. Your Problem is, that your dev server on localhost:3000 is sending an cors header.

    Take a look here: https://create-react-app.dev/docs/proxying-api-requests-in-development/

    Login or Signup to reply.
  2. CORS is ASP.NET is added in two steps:

    1. Add required services which is done in ConfigureServices in Startup
    2. Add CORS middleware which is done in Configure in Startup

    From what you’ve shown I assume you’ve missed step 2. In your Configure method in Startup you should add call to UseCors() AFTER UseRouting().

    Here is the official page about CORS. Note: examples there are using .NET 6 minimal api, but the idea stays the same – add services then add middleware.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search