跨域 header
webserver 端可在 http response 响应头中添加如下字段:
Access-Control-Allow-Origin http://www.my.com (注意默认没有 /)
Access-Control-Allow-Methods POST,GET,PUT,OPTIONS
Access-Control-Allow-Credentials True (跨域带 cookie 须设置此项)
注意 Access-Control-Allow-Origin 中只能填写一个域名,多个域名用 , 分割 a.com , b.com
并不能直接生效(需要再配置 webserver)一个比较取巧的方法是使用动态的域名,即 ctx.request.headers.origin
如果是在 express 或 koa 中
ctx.set('Access-Control-Allow-Methods', 'POST,GET,OPTIONS');
ctx.set('Access-Control-Allow-Origin',ctx.request.headers.origin);
ctx.set('Access-Control-Allow-Credentials', 'true');
ctx.set('Access-Control-Request-Headers', 'Origin, Content-Type, X-CustomHeader, Accept');
web端的配置
js 方面如果希望跨域携带 cookie ,除 webserver 在 http 头添加 Access-Control-Allow-Credentials True
外还需在 ajax 对象设置 xhr.withCredentials = true;
属性。而且只能携带 Access-Control-Allow-Origin
中指定域的 cookie。
杰快瑞 :)
$.ajax({
type: "POST",
url: "http://a.com",
dataType: 'jsonp',
xhrFields: {
withCredentials: true //跨域发送cookies
},
crossDomain: true,
success:function(){
},
error:function(){
}
})
js:
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://a.com", true);
xhr.withCredentials = true; //跨域发送cookies
xhr.send();
跨域预检查 (OPTIONS 请求)
按照 W3C 的规范,跨域的请求分为 简单请求 和 复杂请求
简单请求为 GET
和 Content-Type
为 application/x-www-form-urlencoded 、multipart/form-data 、text/plain
的 POST 请求,这种跨域请求不需要预检查。
其余请求为复杂请求,例如 Content-Type
为 JSON
类型,则再 发出请求前,会预先发送一个 OPTIONS 请求 用来让服务器确认是否该安全。 如果 OPTIONS 预请求返回的是大于 400 的状态码如: 400 404 500 等等,则不会再继续发送 POST 请求。 具体请点击这: HTTP访问控制(CORS)