跨域怎么解决 1.JSONP 只支持get请求,不支持post请求 网页中添加script标签,向服务器请求json数据,服务器收到请求,将数据放在一个指定名字的回调函数的参数位置传回来 注意点:向服务器发送请求,该请求的查询字符串的callback参数,用来指定回调函数的名字
// 向服务器test.com发出请求,该请求的查询字符串有一个callback参数,用来指定回调函数的名字
// 处理服务器返回回调函数的数据
2.jQuery ajax dataType请求方式为JSONP 自定义回调函数名
$.ajax({ url: 'www.test.com:8080/login', type: 'get', dataType: 'jsonp', // 请求方式为jsonp jsonpCallback: "handleCallback", // 自定义回调函数名 data: {} });
3.vue.js this.$http.jsonp('www.domain2.com:8080/login', { params: {}, jsonp: 'handleCallback' }).then((res) => { console.log(res);
})
4.CORS
CORS 是跨域资源分享(Cross-Origin Resource Sharing)的缩写。它是 W3C 标准,属于跨源 AJAX 请求的根本解决方法。
1、普通跨域请求:只需服务器端设置Access-Control-Allow-Origin
2、带cookie跨域请求:前后端都需要进行设置
【前端设置】根据xhr.withCredentials字段判断是否带有cookie <1原生ajax
var xhr = new XMLHttpRequest(); // IE8/9需用window.XDomainRequest兼容
// 前端设置是否带cookie xhr.withCredentials = true;
xhr.open('post', 'www.domain2.com:8080/login', true); xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xhr.send('user=admin');
xhr.onreadystatechange = function() { if (xhr.readyState == 4 && xhr.status == 200) { alert(xhr.responseText); }
}; <2jQuery ajax
$.ajax({ url: 'www.test.com:8080/login', type: 'get', data: {}, xhrFields: { withCredentials: true // 前端设置是否带cookie }, crossDomain: true, // 会让请求头中包含跨域的额外信息,但不会含cookie }); <3vue-resource
Vue.http.options.credentials = true <4 axios
axios.defaults.withCredentials = true
5.设置document.domain解决无法读取非同源网页的 Cookie问题
因为浏览器是通过document.domain属性来检查两个页面是否同源,因此只要通过设置相同的document.domain,两个页面就可以共享Cookie(此方案仅限主域相同,子域不同的跨域应用场景。)
// 两个页面都设置 document.domain = 'test.com';
6.跨文档通信 API:window.postMessage()
调用postMessage方法实现父窗口test1.com向子窗口http://test2.com发…
它可用于解决以下方面的问题:
页面和其打开的新窗口的数据传递 多窗口之间消息传递 页面与嵌套的iframe消息传递 上面三个场景的跨域数据传递