ajax跨域访问请求头origin 为null,ajax 跨域请求报No 'Access-Control-Allow-Origin' header is present on the requeste...

支持XMLHttpRequest跨域访问需要在服务端响应添加头信息

Access-Control-Allow-Origin: http://otherSite.com

Access-Control-Allow-Credentials: true

Access-Control-Allow-Methods POST,GET

Access-Control-Allow-Headers Content-Type, Authorization, X-Requested-With

Access-Control-Allow-Origin:必须设置,如果没有设置会导致跨域访问失败。它的值有两种:一是限定单一访问来源,如“http://otherSite.com”,二是不限访问来源,直接把值设为“*”即可

Access-Control-Allow-Credentials:可选,默认情况下,跨域访问不会带cookie信息,如果需要带上cookie信息,则需要把Access-Control-Allow-Credentials设为true。

Access-Control-Allow-Methods: 设置允许tttp请求的方法

Access-Control-Allow-Headers: 设置允许http请求的头信息

跨域请求带cookie,除了服务端设置Access-Control-Allow-Credentials设为true外,客户端也需要设置ajax的withCredentials为true,例如

$.ajax({

url: 'http://otherSite.com/api',

type: 'POST',

contentType:'application/json',

data: JSON.stringify(arr[0]),

xhrFields: {

withCredentials: true

},

success: function(data){

alert(data);

}

});