2016-05-25 79 views
0

儘管我配置了我的商店的標頭配置,但得到如下錯誤:No 'Access-Control-Allow-Origin' header is present on the requested resourceExtJS - 將標頭添加到AJAX商店

這裏是Ext.data.Storeproxy配置:爲request

proxy  : { 
     type : 'ajax', 
     headers : { 
      'Access-Control-Allow-Origin': '*', 
      'Access-Control-Allow-Methods': 'POST, GET, OPTIONS, DELETE, PUT', 
      'Access-Control-Max-Age': '1000', 
      'Access-Control-Allow-Headers': 'x-requested-with, Content-Type, origin, authorization, accept, client-security-token' 
     }, 
     api  : { 
      read   : 'https://myurl.com' 
     }, 
     reader : { 
      type   : 'json', 
      rootProperty : 'data', 
      successProperty : 'success', 
      totalProperty : 'totalCount' 
     }, 
     writer : { 
      type   : 'json', 
      writeAllFields : true, 
      encode   : true, 
      rootProperty : 'data' 
     } 
    } 

Chrome的網絡預覽:

Accept:*/* 
Accept-Encoding:gzip, deflate, sdch 
Accept-Language:en,en-US;q=0.8,tr;q=0.6 
Access-Control-Request-Headers:access-control-allow-headers, access-control-allow-methods, access-control-allow-origin, access-control-max-age, x-requested-with 
Access-Control-Request-Method:GET 
Cache-Control:max-age=0 
Connection:keep-alive 
Host:xyz.com 
Origin:http://localhost:9090 
Referer:http://localhost:9090/ 
User-Agent:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36 

回答

2

您不必頭添加到店。您必須將頭添加到商店請求的資源中,因爲位於不同服務器上的後端必須指示存儲在服務器上的腳本被允許使用後端服務器交付的數據。

E.g.如果您使用的是C#的WebAPI後端,創建一個自定義標題過濾

public class AddCustomHeaderFilter : ActionFilterAttribute 
{ 
    public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext) 
    { 
     try 
     { 
      actionExecutedContext.Response.Content.Headers.Add("Access-Control-Allow-Origin", "*"); 
     } 
     catch { } 
    } 
} 

,或者如果您使用的是PHP後臺,

header('content-type: application/json; charset=utf-8'); 
header("Access-Control-Allow-Origin: *"); 

僅舉兩種可能的方式。搜索「Set Access-Control-Allow-Origin header < yourBackendTechnology>」,你應該找到幾十個關於這個問題的SO帖子。

如果您使用第三方的後端,那麼您運氣不好。您必須要求第三方將您的服務器列入白名單,或者使用您自己的服務器作爲代理。

0

典型的訪問控制原點問題。這個問題需要在服務器端而不是客戶端解決。 我已經通過將以下代碼添加到Global.asax.cs文件中來完成它

protected void Application_BeginRequest(object sender, EventArgs e) 
    { 
     HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*"); 

     if (HttpContext.Current.Request.HttpMethod == "OPTIONS") 
     { 
      //These headers are handling the "pre-flight" OPTIONS call sent by the browser 
      HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE"); 
      HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "X-Requested-With,Content-Type"); 
      HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept"); 
      HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000"); 
      HttpContext.Current.Response.End(); 
     } 
    }