2016-05-25 78 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(); 
     } 
    }