简体   繁体   English

尝试执行本地主机 API 时,在 ReactJS 应用程序中出现 CORS 错误

[英]Getting CORS error in ReactJS app when attempting to execute localhost API

I'm attempting to create a simple app to do some AES encryption (required for work).我正在尝试创建一个简单的应用程序来进行一些 AES 加密(工作所需)。 I created a small app in ReactJS that has a textbox for the plain text, a button that calls the encrypt method, and then a readonly textbox that displays the encrypted value.我在 ReactJS 中创建了一个小应用程序,它有一个纯文本文本框、一个调用 encrypt 方法的按钮,以及一个显示加密值的只读文本框。

The encrypt method calls an API that I wrote with ASP.NET Core (lives locally for now) to test the encryption out. encrypt 方法调用我用 ASP.NET Core(目前位于本地)编写的 API 来测试加密。 The API successfully encrypts and returns the encrypted value when I execute in Postman and/or the browser but when I do it through my React app it throws the CORS error.当我在 Postman 和/或浏览器中执行时,API 成功加密并返回加密值,但是当我通过我的 React 应用程序执行此操作时,它会引发 CORS 错误。

I'm extremely new at both creating API's and React so apologies in advance if the fix is a very simple one.我在创建 API 和 React 方面都非常陌生,所以如果修复非常简单,请提前道歉。

Here is my Startup class in the API project:这是我在 API 项目中的Startup class:

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();
        });

    }
}

And then here is my encrypt method in the React app:然后这是我在 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));
}

Here's the error from the browser console:这是来自浏览器控制台的错误:

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).

I don't know do we have the same CORS problem, but once I solved that problem with these changes: Adding this line in package.json file:我不知道我们是否有相同的 CORS 问题,但是一旦我通过这些更改解决了该问题: 在package.json文件中添加此行:

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

And/or by disabling host checking in .env file:和/或通过禁用主机签入.env文件:

DANGEROUSLY_DISABLE_HOST_CHECK=true

This is not a perfect approach in that this absolutely is not how you want to address the issue in a production environment, but for development purposes you could try this.这不是一个完美的方法,因为这绝对不是您想要在生产环境中解决问题的方式,但出于开发目的,您可以尝试这样做。

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

This would be in place of your current UseCors implementation.这将代替您当前的UseCors实现。 The problem with your current implementation is that (if properly syntaxed) would only allow CORS from itself.您当前实现的问题是(如果语法正确)仅允许 CORS 本身。 You need to allow CORS from the source of your node server (or whatever domain/port is running your web app).您需要从节点服务器的源(或运行 web 应用程序的任何域/端口)允许 CORS。 Since you do not indicate that in your post, * covers everything (very unsafe, as a reminder, for production).由于您没有在帖子中指出这一点,因此*涵盖了所有内容(非常不安全,提醒一下,对于生产而言)。

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

相关问题 尝试执行多个命令时出现错误 - Getting an error when attempting to execute multiple commands 我在 ASP.NET Core Web API 应用程序上配置 CORS 时出现 CORS 错误 - I'm getting CORS error with CORS configured on ASP.NET Core Web API app 调用我的 API 时在我的反应应用程序上出现此 CORS 错误 - 请求的资源上不存在“Access-Control-Allow-Origin” header - Getting this CORS error on my react app when calling my API - No 'Access-Control-Allow-Origin' header is present on the requested resource 尝试保存分数时出错? - Getting error when attempting to save score? .Net 5 Web API CORS LocalHost - .Net 5 Web API CORS LocalHost 尝试执行FetchXml查询时出现“通用SQL错误” - “Generic SQL Error ”when attempting to execute a FetchXml query 尝试使用c#执行查询时SqlCommand返回错误 - SqlCommand is returning an error when attempting to execute a query using c# CefSharp CORS 向本地主机请求错误 - CefSharp CORS error on request to localhost 尝试将数据导入EPiServer时出现400错误 - I'm getting a 400 Error when attempting to import data into EPiServer .net API 尝试接受带有大文件的 model 时出错 - .net API error when attempting to accept model with large file
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM