.net core實現前後端徹底分離
阿新 • • 發佈:2018-09-14
方法 red app rtu runtime query exception get header
問題的關鍵在跨域
1.我們在services裏面 添加跨域內容如下:
public void ConfigureServices(IServiceCollection services) { //這個AddOcelot方法是Ocelot包給IServiceCollection擴展的方法 services.AddOcelot(configuration).AddConsul(); #region CORS services.AddCors(c => {//↓↓↓↓↓↓↓註意正式環境不要使用這種全開放的處理↓↓↓↓↓↓↓↓↓↓ c.AddPolicy("AllRequests", policy => { policy .AllowAnyOrigin()//允許任何源 .AllowAnyMethod()//允許任何方式 .AllowAnyHeader()//允許任何頭 .AllowCredentials();//允許cookie }); //↑↑↑↑↑↑↑註意正式環境不要使用這種全開放的處理↑↑↑↑↑↑↑↑↑↑ //一般采用這種方法 c.AddPolicy("LimitRequests", policy => { policy .WithOrigins("http://localhost:8020", "http://blog.core.xxx.com", "")//支持多個域名端口.WithMethods("GET", "POST", "PUT", "DELETE")//請求方法添加到策略 .WithHeaders("authorization");//標頭添加到策略 }); }); #endregion }
2.在中間件中添加跨域內容
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } #region 跨域相關 app.UseCors("AllRequests"); #endregion //app.Run(async (context) => //{ // await context.Response.WriteAsync("Hello World!"); //}); app.UseOcelot().Wait(); }
註意如果項目沒有用ocelot 直接是請求webapi 我們上述內容寫在webapi的startup文件中
如果項目使用了ocelot 那麽我們的上述內容只需要寫在ocelot項目中
3.跨域請求 get沒什麽問題 但是post要註意:
post請求傳遞參數要有如下代碼:
一個完整的例子:
<html> <head> <meta charset="utf-8" /> <title>請求</title> <script type="text/javascript" src="js/jquery-1.8.3.js"></script> <script type="text/javascript"> $.ajax({ type: "post", url: "https://www.xxx.net/xxxService/Category/AddCategory", data: JSON.stringify({ "CategoryName": "類別", "Code": 4 }), contentType:"application/json", success: function(data) { console.log(data); }, error: function() { console.log("請求錯誤") } }); </script> </head> <body> </body> </html>
done!
.net core實現前後端徹底分離