对跨域的理解
最近在写项目的时候遇到了跨域的问题,然后整理两个跨域的方法,以下是自己的见解。
什么是跨域呢?当两个地址在协议、主机或者端口不一致的时候,即判定为跨域。
当前端请求服务器的时候出现跨域,那么前端就会报错,一般错误为:
XMLHttpRequest cannot load http://xxx.xxx.xxx/xxxxx/xxxxx.
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://127.0.0.1:8020' is therefore not allowed access.
那么可以有两种解决方法(以jquery的ajax为例):
第一种方法使用jsonp:
$.ajax("http://xxx.xxx.xxx/xxx/xxx", {
type: 'get',
dataType: "jsonp",
data : reqData
success: function(data) {
console.log(data);
},
error: function(xhr, type, errorThrown) {
//异常处理;
console.log(xhr.statusText);
plus.nativeUI.toast("fail");
}
});
使用jsonp一定要注意代码里面红色的文字。首先jsonp只支持get请求,所以所有传入的参数都是 http://xxx.xxx.xxx/xxx/xxx?xxx=1&&yyy=2 这种形式;其次在dataType属性必须设置为jsonp,jquery是支持jsonp的。
这个方法适用于比较简单的请求,而且对数据安全要求不高、参数较小的请求。
那么,我假如要用post怎么办?数据比较大怎么办?登录的时候总不能要求使用get方法吧?
第二种方法使用CORS:
CORS支持post跨域,可以很好解决jsonp的缺陷。
CORS其实很简单,就是需要在服务器加入 (Access-Control-Allow-Origin:*),这里的*表达任何请求URL都可以跨域,为了安全考虑,*可以更改为你的请求地址。
那么ajax该怎么写?ajax就是很正常的写了。
$.ajax("http://xxx.xxx.xxx/xxx/xxx", {
type: 'post',
dataType: "json",
data : reqData
success: function(data) {
console.log(data);
},
error: function(xhr, type, errorThrown) {
//异常处理;
console.log(xhr.statusText);
plus.nativeUI.toast("fail");
}
});
以上是我对跨域两种方法的理解,经过测试都通过了。但是我觉得自己还有必要深入去理解它。
浙公网安备 33010602011771号