AJAX跨域原因及解决方法

一. 什么是跨域?

     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 {
我在测试时发现,此注解加上后仍然有一些跨域问题出现。所用推荐 使用 增加过滤器 的方法。


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值