天天看點

jQuery調用WebAPI報錯“已攔截跨源請求:同源政策禁止讀取位于...的遠端資源”’

  前篇文章介紹了在VSCode中建立WebAPI,後續在asp.net core mvc項目中用jQuery調用WebAPI擷取環境檢測資料,調用的示例代碼如下所示,但是在調用過程中報下圖的錯誤,即“已攔截跨源請求:同源政策禁止讀取位于…的遠端資源”

$("#showChart").click(function()
            {
                $.getJSON("http://localhost:5003/api/EMData",function(data){
                     var str="<table ;
                    str +="<tr>";
                    for(var name in data[0])
                    {
                        str +="<th>"+name+"</th>";                 
                    }

                    str += "</table>";
                    $("#chartDiv").html(str);                                   
                });                
            })
           
jQuery調用WebAPI報錯“已攔截跨源請求:同源政策禁止讀取位于...的遠端資源”’

  百度錯誤資訊,并根據一些檔案進行了代碼調整(詳見參考文獻1-3),包括修改火狐浏覽器安全設定、将localhost改為120.0.0.1等,但是都沒有起作用。

  後面根據參考文獻4,在WebAPI項目的startup檔案中ConfigureServices和Configure函數增加以下代碼:

// ConfigureServices函數增加下列代碼
 services.AddCors(options =>
				  options.AddPolicy("cors",
				  p => p.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod().AllowCredentials()));

	// Configure函數增加下列代碼
	app.UseCors("cors");
           

  項目編譯成功,但是運作項目時報下列錯誤:

jQuery調用WebAPI報錯“已攔截跨源請求:同源政策禁止讀取位于...的遠端資源”’

  繼續百度錯誤資訊,找到了參考文獻5,根據文獻中的說明,在startup檔案的ConfigureServices和Configure函數中增加Cors相關配置的思路是對的(參考文獻6中對Cors有詳細介紹),但是代碼的調用方式及順序很重要,Cors配置不能同時啟用 AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader() .AllowCredentials(),否則就會報錯,同時app.UseCors必須放在app.UseAuthorization();代碼後面。于是對startup檔案中的代碼進行調整,調整後的代碼如下:

public void ConfigureServices(IServiceCollection services)
        {
        		//下列代碼來自參考文獻5
            services.AddCors(options =>
            {
                options.AddPolicy("any", builder =>
                {
                    builder.WithMethods("GET", "POST", "HEAD", "PUT", "DELETE", "OPTIONS")
                .AllowAnyOrigin(); //允許任何來源的主機通路
                });
            });

            services.AddControllersWithViews();
            services.AddDbContext<EnvironmentMonitorContext>();                
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
        			...
        			...
        			
            app.UseStaticFiles();

            app.UseRouting();
            

            app.UseAuthorization();

            app.UseCors("any");

            ...
            ...
        }
           

  至此問題解決,使用jQuery可以順利的調用WebAPI擷取資料。

參考文獻:

[1]https://blog.csdn.net/daBai_Zzz/article/details/101292073

[2]https://blog.csdn.net/qq_44081582/article/details/106449398

[3]https://blog.csdn.net/daBai_Zzz/article/details/101292073?utm_medium=distribute.pc_relevant_t0.none-task-blog-2%7Edefault%7ECTRLIST%7Edefault-1.no_search_link&depth_1-utm_source=distribute.pc_relevant_t0.none-task-blog-2%7Edefault%7ECTRLIST%7Edefault-1.no_search_link

[4]https://www.cnblogs.com/dotnet261010/p/10177166.html

[5]https://blog.csdn.net/qq_36535245/article/details/106171793

[6]https://docs.microsoft.com/zh-cn/aspnet/core/security/cors?view=aspnetcore-5.0