Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

367
Vistas
ASP.NET Core API not accessible from React.js (CORS)

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.

about 4 years ago · Santiago Gelvez
2 Respuestas
Responde la pregunta

0

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.

about 4 years ago · Santiago Gelvez Denunciar

0

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/

about 4 years ago · Santiago Gelvez Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda