【问题标题】:Trying to Fetch data from a localhost web api end point from react app - NoCors error尝试从反应应用程序的本地主机 Web api 端点获取数据 - Cors 错误
【发布时间】:2020-08-25 21:30:59
【问题描述】:

我在 csharp web api 中创建了一个端点,它返回一些 json 数据,它在邮递员上运行良好。 但是当我在我的反应应用程序上尝试相同的网址时,我收到以下错误

反应代码

fetch('https://localhost:44391/agency')
  .then(response => response.json())
  .then(json => console.log(json))

错误

Access to fetch at 'https://localhost:44391/agency' from origin 'http://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.

我点击了这个链接Trying to use fetch and pass in mode: no-cors 并尝试了以下代码

fetchData () {
           var proxyUrl = 'https://cors-anywhere.herokuapp.com/',
    targetUrl = 'https://localhost:44391/agency'
fetch(proxyUrl + targetUrl)
        .then(blob => blob.json())
        .then(data => {
            console.log(data);
            return data;
        })
        .catch(e => {
            console.log(e);
            return e;
        });
      }

我收到此错误

GET https://cors-anywhere.herokuapp.com/https://localhost:44391/agency 404 (Not Found)
SyntaxError: Unexpected token N in JSON at position 0

注意 我无法执行的链接中的步骤是

git clone https://github.com/Rob--W/cors-anywhere.git - 完成

cd cors-anywhere/ - 完成

npm 安装 - 完成

heroku create - 不能这样做。我需要 HEROKU,我不知道为什么

git push heroku master - 还没有完成

非常感谢您的帮助

谢谢 P

更新

我已经通过链接https://docs.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-3.1#dp 在我的 c# web api 上启用了 CORS

我关注的部分是CORS with default policy and middleware

我的代码如下

我尝试过options.AddPolicyoptions.AddDefaultPolicy,但是当我从 react 应用程序调用时它仍然不起作用

namespace React_NalONE_API
{
    public class Startup
    {
        readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
        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(options =>
            {
                // options.AddPolicy(name: MyAllowSpecificOrigins,
                //                 builder =>
                //               {
                //                 builder.WithOrigins("http://localhost/*",
                //                                   "https://localhost/*");
                //         });

                options.AddDefaultPolicy(
                builder =>
                {
                    builder.WithOrigins("http://localhost/*",
                                        "https://localhost/*");
                });
            });
            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)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseCors();

            app.UseAuthorization();

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

【问题讨论】:

  • 如果 Web API 在 localhost 上,您可以通过从 API 响应中添加适当的标头来修改它。如果您对OPTIONS 方法的响应缺少Access-Control-Allow-Origin,则尤其会发生这种情况,其中标头值需要是*(如果不使用凭据)或请求来源(由请求Origin 标头指定)。

标签: javascript c# reactjs asp.net-web-api asp.net-core-webapi


【解决方案1】:

如果您只是想在本地进行测试,则不需要 Heroku。我假设您使用的教程中的那一点只是为了部署应用程序,以展示它的功能。您不一定需要遵循这一点来让一切正常工作。

问题似乎与 CORS 权限有关,通常浏览器不允许您发出 CORS 请求,除非您请求的来源的响应包含正确的 CORS 标头。我会检查this 以了解更多上下文。

如果启用 CORS 是您想要做的事情,那么您可能想要 enable CORS in .NET(我假设您使用的是 .NET - 无论您使用什么框架,都应该有一种方法可以启用CORS)

【讨论】:

  • 嗨@Raghav 感谢您的回复,很抱歉回复晚了,我确实尝试了您的建议。是的,我在本地主机上有一个 c# web api。我按照您的链接并使用CORS with default policy and middleware 在 web api 上启用了 cors。我将使用 c# 代码更新我的问题。在 react 应用程序上,我在没有任何代理的情况下调用,但仍然出现相同的错误,所以这个问题是 react 或 c#
  • 看看这个? daveceddia.com/…
猜你喜欢
  • 1970-01-01
  • 2019-07-30
  • 1970-01-01
  • 2020-11-20
  • 2019-11-09
  • 1970-01-01
  • 1970-01-01
  • 2017-12-22
  • 2018-07-31
相关资源
最近更新 更多