【问题标题】:Getting CORS error in ReactJS app when attempting to execute localhost API尝试执行 localhost API 时在 ReactJS 应用程序中出现 CORS 错误
【发布时间】:2020-08-27 04:38:36
【问题描述】:

我正在尝试创建一个简单的应用程序来进行一些 AES 加密(工作所需)。我在 ReactJS 中创建了一个小应用程序,它有一个纯文本文本框、一个调用 encrypt 方法的按钮,以及一个显示加密值的只读文本框。

加密方法调用我用 ASP.NET Core(目前位于本地)编写的 API 来测试加密。当我在 Postman 和/或浏览器中执行时,API 成功加密并返回加密值,但是当我通过我的 React 应用程序执行时,它会引发 CORS 错误。

我在创建 API 和 React 方面都非常陌生,所以如果修复非常简单,请提前道歉。

这是我在 API 项目中的Startup 类:

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddCors();
        services.AddControllers();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        app.UseCors(
            options => options.WithOrigins("https://localhost:5001/encryption/encrypt").AllowAnyMethod()
        );

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseHttpsRedirection();

        app.UseRouting();

        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });

    }
}

然后这是我在 React 应用程序中的 encrypt 方法:

encrypt() {
var plainText = this.textToEncrypt.value;
console.log(plainText);

var requestOptions = {
  method: 'GET',
  headers: {
    'Access-Control-Allow-Origin' : '*'
  }
};

fetch("https://localhost:5001/encryption/encrypt?plainText=" + plainText, requestOptions)
  .then(response => response.text())
  .then(data => this.setState({ encryptedText: data.value }))
  // .then(result => console.log(result))
  .catch(error => console.log('error', error));
}

这是来自浏览器控制台的错误:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://localhost:5001/encryption/encrypt?plainText=sample%20text. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).

【问题讨论】:

  • 查看您的网络应用程序和 api 请求中的网络标头。如果您没有看到Access-Control-Allow-Origin: *,那么您需要再看一下您的配置。 Arm 的回答中描述的代理方法是一种很好的解决方法,可以避免调整网络标头,这对于生产环境来说是一种不安全的方法。
  • 和 fwiw,Access-Control-Allow-Origin 是响应标头,而不是请求标头,因此不需要将其包含在您的 fetch 中(它不会有任何影响)。跨度>

标签: c# reactjs cors


【解决方案1】:

这不是一个完美的方法,因为这绝对不是您想要在生产环境中解决问题的方式,但出于开发目的,您可以尝试一下。

if (env.IsDevelopment())
{
    app.UseCors(
        options => options.WithOrigins("*").AllowAnyMethod()
    );
}

这将代替您当前的UseCors 实现。您当前实现的问题是(如果语法正确)只允许来自其自身的 CORS。您需要允许来自节点服务器源(或运行您的 Web 应用程序的任何域/端口)的 CORS。由于您没有在帖子中指出,* 涵盖了所有内容(非常不安全,提醒一下,对于生产而言)。

【讨论】:

  • 这实际上是我需要做的,所以我至少可以继续。当我们需要时,让实际的开发人员找出生产方法:)
【解决方案2】:

我不知道我们是否有同样的 CORS 问题,但是一旦我通过这些更改解决了这个问题: 在 package.json 文件中添加这一行:

"proxy": "http(s)://backend.url/api",

和/或通过在 .env 文件中禁用主机检查:

DANGEROUSLY_DISABLE_HOST_CHECK=true

【讨论】:

  • 如果您使用代理方法,他需要更改他的获取 URL 以指向运行他的 Web 应用程序的(可能是节点)服务器,而不是运行他的 API 的(可能是 IIS express)服务器以及调整 URL 路径以包含代理子文件夹(即:在您的示例中为 /api)。
猜你喜欢
  • 2019-11-09
  • 2021-10-30
  • 2020-06-10
  • 2013-04-30
  • 2021-09-24
  • 2019-07-01
  • 2019-01-23
  • 2019-07-06
  • 2018-06-19
相关资源
最近更新 更多