Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

369
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda