简体   繁体   English

无法从 React.js (CORS) 访问 ASP.NET Core API

[英]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.我正在开发一个使用 React 作为前端和 ASP.NET Core 作为后端的 Web 应用程序。

This is code from my Startup.cs .这是来自我的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.这是我的完整 API 控制器,在 Visual Studio 2022 中使用 ISS 进行调试时,它在 Chrome 中运行良好。

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.这是调用 API 的 React 代码。

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:执行 React 代码时,我在 Chrome 控制台中收到此错误:

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. CORS 策略阻止了从源“https://localhost:5001/Api/Login”获取的访问权限:没有“Access-Control-Allow-Origin”标头请求的资源。 If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.如果不透明的响应满足您的需求,请将请求的模式设置为“no-cors”以获取禁用 CORS 的资源。

I'm new to both ASP.NET and React so any kind of help or tip is welcome.我是 ASP.NET 和 React 的新手,因此欢迎任何形式的帮助或提示。 If you need more info I'll edit the question.如果您需要更多信息,我将编辑问题。

CORS is ASP.NET is added in two steps: CORS 是 ASP.NET 的添加分两步:

  1. Add required services which is done in ConfigureServices in Startup添加在Startup中的ConfigureServices中完成的所需服务
  2. Add CORS middleware which is done in Configure in Startup添加在Startup中的Configure中完成的 CORS 中间件

From what you've shown I assume you've missed step 2 .根据您所展示的内容,我假设您错过了step 2 In your Configure method in Startup you should add call to UseCors() AFTER UseRouting() .StartupConfigure方法中,您应该在 UseRouting()之后添加对UseCors() UseRouting()调用。

Here is the official page about CORS. 是关于CORS的官方页面。 Note: examples there are using .NET 6 minimal api, but the idea stays the same - add services then add middleware.注意:示例使用 .NET 6 最小 api,但想法保持不变 - 添加服务然后添加中间件。

Your Problem is, that your dev server on localhost:3000 is sending an cors header.您的问题是,您在 localhost:3000 上的开发服务器正在发送一个 cors 标头。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM