本文的目的是介绍Access-Control-Allow-Origin:ajax跨域访问的详细情况,特别关注ajax跨域调用的相关信息。我们将通过专业的研究、有关数据的分析等多种方式,为您呈现一个全面
本文的目的是介绍Access-Control-Allow-Origin:ajax 跨域访问的详细情况,特别关注ajax跨域调用的相关信息。我们将通过专业的研究、有关数据的分析等多种方式,为您呈现一个全面的了解Access-Control-Allow-Origin:ajax 跨域访问的机会,同时也不会遗漏关于(服务端处理)ajax 设置Access-Control-Allow-Origin实现跨域访问、.Net 通过设置Access-Control-Allow-Origin来实现跨域访问、Access-Control-Allow-Origin 与 Ajax 跨域、Access-Control-Allow-Origin 标头如何工作? - How does Access-Control-Allow-Origin header work?的知识。
本文目录一览:- Access-Control-Allow-Origin:ajax 跨域访问(ajax跨域调用)
- (服务端处理)ajax 设置Access-Control-Allow-Origin实现跨域访问
- .Net 通过设置Access-Control-Allow-Origin来实现跨域访问
- Access-Control-Allow-Origin 与 Ajax 跨域
- Access-Control-Allow-Origin 标头如何工作? - How does Access-Control-Allow-Origin header work?
Access-Control-Allow-Origin:ajax 跨域访问(ajax跨域调用)
在使用jquery的$.ajax跨域访问的时候,如客户端域名是www.test.com,而服务器端是www.test2.com,在客户端通过ajax访问服务器端的资源将会报跨域错误:
XMLHttpRequest cannot load http://www.test2.com/test.PHP. No 'Access-Control-Allow-Origin' header is present on the requested resource.Origin 'http://www.test.com' is therefore not allowed access.
ajax跨域访问的解决方法很多,很多人推荐JSONP方法,这种方法只支持GET方式,不如POST方式安全。有兴趣的可以自行搜索,这里讲另外一种方法。
这时候只要在被请求的响应头中加入下面语句:
// 指定允许其他域名访问 header('Access-Control-Allow-Origin:*'); // 响应类型 header('Access-Control-Allow-Methods:POST'); // 响应头设置 header('Access-Control-Allow-Headers:x-requested-with,content-type');
就可以实现跨域请求了。
Access-Control-Allow-Origin:*表示允许任何域名跨域访问
如果需要指定某域名才允许跨域访问,只需把Access-Control-Allow-Origin:*改为Access-Control-Allow-Origin:允许的域名
eg:header('Access-Control-Allow-Origin:http://www.test.com');
(服务端处理)ajax 设置Access-Control-Allow-Origin实现跨域访问
原文:http://www.jb51.cc/article/p-harvrahb-bkb.html
ajax跨域访问是一个老问题了,解决方法很多,比较常用的是JSONP方法,JSONP方法是一种非官方方法,而且这种方法只支持GET方式,不如POST方式安全。
即使使用jquery的jsonp方法,type设为POST,也会自动变为GET。
官方问题说明:
“script”: Evaluates the response as JavaScript and returns it as plain text. disables caching by appending a query string parameter,“_=[TIMESTAMP]“,to the URL unless the cache option is set to true.Note: This will turn POSTs into GETs for remote-domain requests.
如果跨域使用POST方式,可以使用创建一个隐藏的iframe来实现,与ajax上传图片原理一样,但这样会比较麻烦。
因此,通过设置Access-Control-Allow-Origin来实现跨域访问比较简单。
例如:客户端的域名是www.client.com,而请求的域名是www.server.com
如果直接使用ajax访问,会有以下错误
XMLHttpRequest cannot load http://www.server.com/server.PHP. No 'Access-Control-Allow-Origin' header is present on the requested resource.Origin 'http://www.client.com' is therefore not allowed access.
在被请求的Response header中加入
- //指定允许其他域名访问
- header('Access-Control-Allow-Origin:*');
- //响应类型
- header('Access-Control-Allow-Methods:POST');
- //响应头设置
- header('Access-Control-Allow-Headers:x-requested-with,content-type');
就可以实现ajax POST跨域访问了。
代码如下:
client.html路径:http://www.client.com/client.html
.Net 通过设置Access-Control-Allow-Origin来实现跨域访问
[toc]
# 前言
.Net 通过设置Access-Control-Allow-Origin来实现跨域访问,具体哪里可以设置Access-Control-Allow-Origin呢?
- web.config中可以设置;
- 在IIS服务器站点的功能视图中设置HTTP响应标头;
- 通过nginx代理服务器进行设置;
- 在每个api接口上添加响应头;
- 写一个拦截器,应用到所有控制器上,在拦截器里控制来访域名,动态设置Access-Control-Allow-Origin的值;
本文主要详细说下第四种和第五种方式,第五种方式也是对第四种方式的一种封装;
# 为每个API接口单独添加响应头
1、针对 ASP.NET MVC 项目的Controllers
public class Default1Controller : Controller
{
public ActionResult Test()
{
ControllerContext.HttpContext.Response.Headers.Add("Access-Control-Allow-Origin", "*");
/*
--Your code
*/
return Json("hello");
}
}
2、针对 ASP.NET Web API项目的Controllers
public class TestController : ApiController
{
public HttpResponseMessage Get(int id)
{
var response = Request.CreateResponse(HttpStatusCode.OK, new {Name="lily",age=10});
response.Headers.Add("Access-Control-Allow-Origin", "*");
//response.Headers.Add("X-Pagination", "TestHeader");
//response.Headers.Add("Access-Control-Expose-Headers", "X-Pagination");
return response;
}
}
3、针对ASP.NET Web Forms项目中的处理程序
public class TestHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.AddHeader("Access-Control-Allow-Origin", "http://example.com");
context.Response.AddHeader("Access-Control-Allow-Headers", "*");
context.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
context.Response.AddHeader("Access-Control-Allow-Credentials", "true");
//context.Response.AddHeader("TestHeaderToExpose", "test");
//context.Response.AddHeader("Access-Control-Expose-Headers", "TestHeaderToExpose");
context.Response.ContentType = "text/plain";
context.Response.Write("Hello World");
}
public bool IsReusable
{
get
{
return false;
}
}
}
# 封装一个拦截器,便于应用到控制器及接口上
1、针对 ASP.NET MVC 项目的Controllers
创建一个attribute:
using System.Web.Mvc;
namespace AllowCross.App_Code
{
public class AllowCrossSiteJsonAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Origin", "*");
//actionExecutedContext.Response.Headers.Add("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
//actionExecutedContext.Response.Headers.Add("Access-Control-Allow-Headers", "*");
//actionExecutedContext.Response.Headers.Add("Access-Control-Allow-Credentials", "true");
//context.Response.AddHeader("TestHeader", "test");
//actionExecutedContext.Response.Headers.Add("Access-Control-Expose-Headers", "TestHeader");
base.OnActionExecuting(filterContext);
}
}
}
将该attribute添加到action上:
using AllowCross.App_Code;
namespace AllowCross.Controllers
{
public class Default1Controller : Controller
{
[AllowCrossSiteJson]
public ActionResult Test()
{
return Json("hello");
}
}
}
2、针对 ASP.NET Web API项目
创建一个attribute:
using System.Web.Http.Filters;
namespace WepApiTest.App_Code
{
public class AllowCrossSiteJsonAttribute : ActionFilterAttribute
{
public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
if (actionExecutedContext.Response != null)
{
actionExecutedContext.Response.Headers.Add("Access-Control-Allow-Origin", "*");
//actionExecutedContext.Response.Headers.Add("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
//actionExecutedContext.Response.Headers.Add("Access-Control-Allow-Headers", "*");
//actionExecutedContext.Response.Headers.Add("Access-Control-Allow-Credentials", "true");
//context.Response.AddHeader("TestHeader", "test");
//actionExecutedContext.Response.Headers.Add("Access-Control-Expose-Headers", "TestHeader");
}
base.OnActionExecuted(actionExecutedContext);
}
}
}
将该attribute添加到acion上:
using WepApiTest.App_Code;
namespace WepApiTest.Controllers
{
public class DefaultController : ApiController
{
[AllowCrossSiteJson]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
}
}
也可以将该attribute添加到整个controller上:
using WepApiTest.App_Code;
namespace WepApiTest.Controllers
{
[AllowCrossSiteJson]
public class DefaultController : ApiController
{
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
}
}
3、针对 ASP.NET Web API 2 还可以使用库:Microsoft.AspNet.WebApi.Cors
3.1 使用nuget安装Microsoft.AspNet.WebApi.Cors
使用命令:
Install-Package Microsoft.AspNet.WebApi.Cors
使用管理器:
3.2 打开App_Start/WebApiConfig.cs文件,在WebApiConfig.Register方法中配置WebApi.Cors
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
//配置WebApi.Cors
config.EnableCors();
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
3.3 在Controller上添加[EnableCors]属性
using System.Web.Http;
using System.Web.Http.Cors;
namespace WepApiTest.Controllers
{
[EnableCors(origins: "http://WepApiTest.com", headers: "*", methods: "*")]
public class TestController : ApiController
{
// GET: api/Test
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
}
}
3.3 在Controller中的action上添加[EnableCors]属性
using System.Web.Http;
using System.Web.Http.Cors;
namespace WepApiTest.Controllers
{
public class TestController : ApiController
{
// GET: api/Test
[EnableCors(origins: "http://WepApiTest.com", headers: "*", methods: "*")]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
}
}
3.4 如果想应用到所有的api controller上,在WebApiConfig.Register方法中进行如下配置
using System.Web.Http;
using System.Web.Http.Cors;
namespace WebApplication2
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
//配置WebApi.Cors
var cors = new EnableCorsAttribute("www.example.com", "*", "*");
config.EnableCors(cors);
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
}
3.5 设置origins、HTTP methods、request headers示例
// Allow CORS for all origins. (Caution!)
[EnableCors(origins: "*", headers: "*", methods: "*")]
[EnableCors(origins: "http://www.justsoso.com,http://www.example.com",
headers: "*", methods: "*")]
[EnableCors(origins: "http://www.example.com", headers: "*", methods: "get,post")]
[EnableCors(origins: "http://example.com",
headers: "accept,content-type,origin,x-my-header", methods: "*")]
3.6 Pass credentials in cross-origin requests
Credentials require special handling in a CORS request. By default, the browser does not send any credentials with a cross-origin request. Credentials include cookies as well as HTTP authentication schemes. To send credentials with a cross-origin request, the client must set XMLHttpRequest.withCredentials to true.
Using XMLHttpRequest directly:
var xhr = new XMLHttpRequest();
xhr.open(''get'', ''http://www.example.com/api/test'');
xhr.withCredentials = true;
In jQuery:
$.ajax({
type: ''get'',
url: ''http://www.example.com/api/test'',
xhrFields: {
withCredentials: true
}
In addition, the server must allow the credentials. To allow cross-origin credentials in Web API, set the SupportsCredentials property to true on the [EnableCors] attribute:
[EnableCors(origins: "http://myclient.azurewebsites.net", headers: "*",
methods: "*", SupportsCredentials = true)]
If this property is true, the HTTP response will include an Access-Control-Allow-Credentials header. This header tells the browser that the server allows credentials for a cross-origin request.
If the browser sends credentials, but the response does not include a valid Access-Control-Allow-Credentials header, the browser will not expose the response to the application, and the AJAX request fails.
Be careful about setting SupportsCredentials to true, because it means a website at another domain can send a logged-in user''s credentials to your Web API on the user''s behalf, without the user being aware. The CORS spec also states that ==setting origins to "*" is invalid if SupportsCredentials is true==.
3.7 浏览器支持情况
库Web API CORS是服务端的处理方法,还必须要求客户端支持CORS,支持情况请查看该地址: https://caniuse.com/#feat=cors
# 低版本IE实现跨域
参考:Cross-Domain AJAX for IE8 and IE9
# 参考
Setting Access-Control-Allow-Origin in ASP.Net MVC - simplest possible method Microsoft.AspNet.WebApi.Cors 跨域资源共享 CORS 详解
——————————————————————————————————————————————
原文出处:https://www.cnblogs.com/willingtolove/p/11175599.html
Access-Control-Allow-Origin 与 Ajax 跨域
问题
在某域名下使用 Ajax 向另一个域名下的页面请求数据,会遇到跨域问题。另一个域名必须在 response 中添加 Access-Control-Allow-Origin
的 header,才能让前者成功拿到数据。
这句话对吗?如果对,那么流程是什么样的?
跨域
怎样才能算跨域?协议,域名,端口都必须相同,才算在同一个域。
参考:
- Are different ports on the same server considered cross-domain? (Ajax-wise)
- 同事李栋的博客:跨源资源共享
当跨域访问时,浏览器会发请求吗
这是真正困扰我们的问题,因为我们不清楚浏览器会怎么做。它会不会检查到你要请求的地址不是同一个域的,直接就禁止了呢?
我在 jsbin 上 做了一个试验 ,使用 Chrome 打开。当点击 “Run with Js” 时,控制台上会打出:
XMLHttpRequest cannot load http://google.com/. No ''Access-Control-Allow-Origin'' header is present on the requested resource. Origin ''http://run.jsbin.io'' is therefore not allowed access.
但开发者工具的”Network” 栏并没有任何记录。它到底发请求了没?
我又使用 python -m SimpleHTTPServer
在本地创建了一个小服务器,然后把地址改成它,结果发现在 python 这边的确打印出请求来了,可见浏览器的确发出了请求。
Access-Control-Allow-Origin
现在该 Access-Control-Allow-Origin
出场了。只有当目标页面的 response 中,包含了 Access-Control-Allow-Origin
这个 header,并且它的值里有我们自己的域名时,浏览器才允许我们拿到它页面的数据进行下一步处理。如:
Access-Control-Allow-Origin: http://run.jsbin.io
如果它的值设为 *
,则表示谁都可以用:
Access-Control-Allow-Origin: *
没错,在产品环境中,没人会用 *
你可以阅读下面这篇文章了解更多,并可找到其中的”Run Sample” 链接,实际体验一下:
http://www.html5rocks.com/en/tutorials/cors/
public HttpResponseMessage Get(string fatherId)
{
string str = JsonConvert.SerializeObject(GetAleCategorysByFid(fatherId), Formatting.Indented);
HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(str, Encoding.GetEncoding("UTF-8"), "application/json") };
result.Headers.Add("Access-Control-Allow-Origin", "*");
return result;
}
Access-Control-Allow-Origin 标头如何工作? - How does Access-Control-Allow-Origin header work?
问题:
Apparently, I have completely misunderstood its semantics. 显然,我完全误解了它的语义。 I thought of something like this: 我想到了这样的事情:
- A client downloads javascript code MyCode.js from http://siteA - the origin . 客户端从 http://siteA- origin 下载 javascript 代码 MyCode.js。
- The response header of MyCode.js contains Access-Control-Allow-Origin: http://siteB , which I thought meant that MyCode.js was allowed to make cross-origin references to the site B. MyCode.js 的响应标头包含 Access-Control-Allow-Origin:http:// siteB ,我认为这意味着 MyCode.js 被允许对站点 B 进行跨域引用。
- The client triggers some functionality of MyCode.js, which in turn make requests to http://siteB, which should be fine, despite being cross-origin requests. 客户端触发了 MyCode.js 的某些功能,该功能继而向 http://siteB 发出了请求,尽管这是跨域请求,但仍然可以。
Well, I am wrong. 好吧,我错了。 It does not work like this at all. 它根本不像这样工作。 So, I have read Cross-origin resource sharing and attempted to read Cross-Origin Resource Sharing in w3c recommendation 因此,我阅读了跨域资源共享,并尝试阅读 w3c 建议中的跨域资源共享
One thing is sure - I still do not understand how am I supposed to use this header. 可以确定的一件事 - 我仍然不明白我应该如何使用此标头。
I have full control of both site A and site B. How do I enable the javascript code downloaded from the site A to access resources on the site B using this header? 我对站点 A 和站点 B 都拥有完全控制权。如何使用此标头使从站点 A 下载的 javascript 代码能够访问站点 B 上的资源?
PS 聚苯乙烯
I do not want to utilize JSONP. 我不想利用 JSONP。
解决方案:
参考一: https://stackoom.com/question/id4F/Access-Control-Allow-Origin 标头如何工作参考二: https://oldbug.net/q/id4F/How-does-Access-Control-Allow-Origin-header-work
今天关于Access-Control-Allow-Origin:ajax 跨域访问和ajax跨域调用的分享就到这里,希望大家有所收获,若想了解更多关于(服务端处理)ajax 设置Access-Control-Allow-Origin实现跨域访问、.Net 通过设置Access-Control-Allow-Origin来实现跨域访问、Access-Control-Allow-Origin 与 Ajax 跨域、Access-Control-Allow-Origin 标头如何工作? - How does Access-Control-Allow-Origin header work?等相关知识,可以在本站进行查询。
本文标签: