簡體   English   中英

嘗試從反應應用程序的本地主機 web api 端點獲取數據 - NoCors 錯誤

[英]Trying to Fetch data from a localhost web api end point from react app - NoCors error

我在 csharp web api 創建了一個端點,它返回一些 json 數據,它在 Z03D476861AFDFA8814Z1 上工作正常。 但是當我在我的反應應用程序上嘗試相同的 url 時,我收到以下錯誤

反應代碼

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 克隆https://github.com/Rob--W/cors-anywhere.git - 完成

cd cors-anywhere/ - 完成

npm 安裝 - 完成

heroku 創建 - 不能這樣做 我需要 HEROKU,我不知道為什么

git 推 heroku 主 - 尚未完成

非常感謝您的幫助

謝謝P

更新

I have enabled CORS on my c# web api following the link https://docs.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-3.1#dp

我遵循的部分是CORS with default policy and middleware

我的代碼如下

我已經嘗試過options.AddPolicyoptions.AddDefaultPolicy但是當我從反應應用程序調用時它仍然不起作用

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

如果您只是想在本地進行測試,則不需要 Heroku。 我假設您使用的教程中的那一點只是為了部署應用程序,以展示它的功能。 您不一定需要遵循這一點來讓一切正常工作。

問題似乎與 CORS 權限有關,通常瀏覽器不允許您發出 CORS 請求,除非來自您請求的源的響應包含正確的 CORS 標頭。 我會檢查一下以獲取更多上下文。

If enabling CORS is something you're looking to do, then you probably want to enable CORS in .NET (I'm assuming that you're using .NET - whatever framework you're using, there should be a way to enable CORS)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM