No 'Access-Control-Allow-Origin' header is present on the requested resource.'Ajax跨域访问解决方案...

mac2022-06-30  79

No 'Access-Control-Allow-Origin' header is present on the requested resource.

当使用ajax访问远程服务器时,请求失败,浏览器报如上错误。这是出于安全的考虑,默认禁止跨域访问导致的。

客户端解决方案

$(function($){ var url = 'http://*****/index'; $.ajax(url, { data: { 'cityname': '成都', 'date': '2016.12.12' }, dataType: 'jsonp', crossDomain: true, success: function(data) { if(data && data.resultcode == '200'){ console.log(data.result.today); } } });

 将ajax请求中的dataType属性设置为“jsonp”,jsonp是专门用来解决跨域访问而诞生的。

 

JSONP的使用参考:https://blog.csdn.net/zhoucheng05_13/article/details/78694766

 服务器端解决方案

在服务器端的filter或者servlet里面添加 response.setHeader("Access-Control-Allow-Origin", "*"); “Access-Control-Allow-Origin”表示允许跨域访问,“*”表示允许所有来源进行跨域访问,这里也可以替换为特定的域名或ip。 很显然,这种方式对非网站拥有人员来说是不能做到的。而且此种方式很容易受到CSRF攻击。

 

转载于:https://www.cnblogs.com/xiaoQ0725/p/9070395.html

相关资源:JAVA上百实例源码以及开源项目
最新回复(0)