AJAX跨域原因及解决方法

xiaoxiao2021-02-28  23

一. 什么是跨域?

     JavaScript只能访问和操作自己域下的资源,不能访问和操作其他域下的资源!

     开发中主要是AJAX的post、get等方法调用服务端资源造成跨域。

二. 产出跨域的原因

    跨域问题来源于JavaScript的同源策略,即只有 协议+主机名+端口号 (如存在)相同,则允许相互访问。

   实际上服务端不进行跨域判断,跨越请求可以在服务器正常请求返回数据。

跨域的判断在浏览器判断端主要判断,并且type 类型必须是xhr(xmlHttpRequest)才产生跨域问题。

总结原因:浏览器限制、跨域、类型是xhr(xmlHttpRequest)

三.解决办法及测试

1.针对浏览器限制,修改调用端浏览器设置。不推荐。不可以一个一个修复

2.针对传输类型为 xhr(xmlHttpRequest)

    2.1.使用jsonp。将传输数据的类型修改为 jsonp, 一般不推荐使用,原因是jsonp只能解决get请求并且服务端和调用端都必须更改

3.服务端增加过滤器,将浏览器判断跨域请求的头加上。例如跨域报错:Failed to load http://localhost:8080/get1: No 'Failed to load http://localhost:8080/get1: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8081' is therefore not allowed access. The response had HTTP status code 403.' header is present on the requested resource. Origin 'http://localhost:8081' is therefore not allowed access. The response had HTTP status code 403.

在过滤器增加header 中 Access-Control-Allow-Origin ,其他类似。最终服务端过滤器完整为:

@Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { HttpServletResponse res=(HttpServletResponse)servletResponse; HttpServletRequest req=(HttpServletRequest)servletRequest; String origin = req.getHeader("Origin"); if (!StringUtils.isEmpty(origin)){ res.addHeader("Access-Control-Allow-Origin",origin); } String headers = req.getHeader("Access-Control-Request-Headers"); if (!StringUtils.isEmpty(headers)){ res.addHeader("Access-Control-Allow-Headers",headers); } res.addHeader("Access-Control-Allow-Methods","*"); // 带cookie时候需满足则条件 res.addHeader("Access-Control-Allow-Credentials","true"); // 用于缓存option请求,减少浏览器的判断 res.addHeader("Access-Control-Max-Age","3600"); filterChain.doFilter(servletRequest,servletResponse); }

4.spring中解决跨域比较简单:在方法、类上增加注解 CrossOrigin

@Controller @CrossOrigin public class IndexController {我在测试时发现,此注解加上后仍然有一些跨域问题出现。所用推荐 使用 增加过滤器 的方法。

转载请注明原文地址: https://www.6miu.com/read-2603297.html

最新回复(0)