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

今天做在线充值的时候,从主站系统请求财务系统的资源的时候出现:

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

很久之前也遇到过ajax跨域请求的问题,但是忘了,嘻嘻,所以今天正好记录一下:

什么是跨域???

举个栗子:在A网站中,我们希望使用Ajax来获得B网站中的特定内容。如果A网站与B网站不在同一个域中,那么就出现了跨域访问问题。你可以理解为两个域名之间不能跨过域名来发送请求或者请求数据,否则就是不安全的。跨域访问违反了同源策略,同源策略的详细信息可以点击如下链接:Same-origin_policy; 总而言之,同源策略规定,浏览器的ajax只能访问跟它的HTML页面同源(相同域名或IP)的资源。

需要注意的是主域名不同算跨域,端口不同算跨域,协议不同算跨域

所谓同源是指,域名,协议,端口均相同,不明白没关系,举个栗子:

http://www.123.com/index.html 调用 http://www.123.com/server.PHP (非跨域)

http://www.123.com/index.html 调用 http://www.456.com/server.php (主域名不同:123/456,跨域)

http://abc.123.com/index.html 调用 http://def.123.com/server.php (子域名不同:abc/def,跨域)

http://www.123.com:8080/index.html 调用 http://www.123.com:8081/server.php (端口不同:8080/8081,跨域)

http://www.123.com/index.html 调用 https://www.123.com/server.php (协议不同:http/https,跨域)

请注意:localhost和127.0.0.1虽然都指向本机,但也属于跨域。

  1. 二、什么是JSONP

  2. JSONP(JSON with Padding)是JSON的一种“使用模式”,可用于解决主流浏览器的跨域数据访问的问题。

解决方案

常用的解决方案有两种,可以分为客户端解决方案和服务器端解决方案。先说服务器端解决方案:

服务器端解决方案

在服务器端的filter或者servlet里面添加

response.setHeader("Access-Control-Allow-Origin", "*");

“Access-Control-Allow-Origin”表示允许跨域访问,“*”表示允许所有来源进行跨域访问,这里也可以替换为特定的域名或ip。

很显然,这种方式对非网站拥有人员来说是不能做到的。而且此种方式很容易受到CSRF攻击。

网上给出的解决办法:客户端解决方案:

https://blog.****.net/silyvin/article/details/52382419

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

但是这里我是通过iframe来解决的,

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

在主站中计算出要访问财务的url,通过iframe引入即可

财务中拦下这个url:

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

找到相应的方法:

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

返回要引用的页面:

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

 

跨域小结(为什么form表单提交没有跨域问题,但ajax提交有跨域问题)

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

 

 

参考博客:

https://blog.****.net/wabiaozia/article/details/78771709

https://blog.****.net/ligang2585116/article/details/73072868