CORS跨域请求及实现机制

一、什么是CORS

CORS是一个W3C标准,全称是"跨域资源共享"(Cross-origin resource sharing)。它允许浏览器向跨源服务器,发出XMLHttpRequest请求,从而克服了AJAX只能同源使用的限制。只要服务器实现了CORS接口,就可以跨源通信。

CORS有两种请求,简单请求和非简单请求。

二、同源

跨域就等于从百度访问谷歌的资源,URL由协议、域名、端口和路径组成,如果两个URL的协议、域名和端口相同,则表示他们同源。相反,只要协议域名端口有任何一个的不同,就被当作是跨域。
浏览器采用同源策略,禁止页面加载或执行与自身来源不同的域的任何脚本。

三、现象

假设在服务器8080和8088这2个端口同时挂载不同代码

  • 8088下代码:
	@RequestMapping ("/")
	@ResponseBody
	public String index(HttpServletResponse response) {
		return "跨域内容显示";
	}
  • 8080下代码:
    @RequestMapping("/cors")
    public String cors(HttpServletResponse response) {
        return "/cors";
    }

cors.html

<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="utf-8">
    <title></title>
    <script th:src="@{js/jquery-1.9.1.min.js}"></script>
</head>
<body>
    <button>获取跨域内容</button>
    <p id="p1"></p>
</body>
<script>
  $(function(){
    $("button").click(function(){
      $.ajax({
        type: "post",
        url:"http://localhost:8088/",
        success:function(result){
          $("#p1").html(result);
        }
      });
    });
  });
</script>
</html>

直接访问8088端口的方法时没有任何问题
在这里插入图片描述
如果通过8080端口的ajaxa访问8088的方法时,会报错信息如下

Failed to load http://localhost:8088/: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access.

在这里插入图片描述

四、解决方案

被调用方需要的解决方案:

  • SpringMVC中
public class CorsFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        if (request.getHeader("Access-Control-Request-Method") != null && "OPTIONS".equals(request.getMethod())) {
            // CORS "pre-flight" request
            response.addHeader("Access-Control-Allow-Origin", "*");
            response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
            response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
            response.addHeader("Access-Control-Max-Age", "1800");//30 min
        }
        //This will filter your requests and responses.
        filterChain.doFilter(request, response);
    }
}

web.xml

<filter>
    <filter-name>allowedAccessFilter</filter-name>
    <filter-class>aaa.bbb.ccc.ddd.CorsFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>allowedAccessFilter</filter-name>
    <url-pattern>/registeryuyue/*</url-pattern>
</filter-mapping>
  • SpringBoot法一:
@SpringBootApplication
@Controller
@CrossOrigin (origins = "http://localhost:8080", maxAge = 3600)
public class DemoApplication {

	public static void main(String[] args) {
		SpringApplication.run(DemoApplication.class, args);
	}

	@RequestMapping ("/")
	@ResponseBody
	public String index(HttpServletResponse response) {
		return "跨域内容显示";
	}
}

此方法中 CrossOrigin 注解只可以应用于单个controller,而下面全局配置的方式可以应用于整个工程

  • SpringBoot法二:
package com.pzh.cros.demo;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

/**
 * 实现基本的跨域请求
 */
@Configuration
public class CorsConfig {
    private CorsConfiguration buildConfig() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.setMaxAge(3600L); // 表明在3600秒内,不需要再发送预检验请求
        corsConfiguration.addAllowedOrigin("http://localhost:8080"); // 允许http://localhost:8080域名使用
        corsConfiguration.addAllowedHeader("*"); // 允许任何头
        corsConfiguration.addAllowedMethod("*"); // 允许任何方法(post、get等)
        return corsConfiguration;
    }

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", buildConfig()); // 对接口配置跨域设置
        return new CorsFilter(source);
    }
}

  • Nginx配置
    在这里插入图片描述

五、CORS常见的header

Access-Control-Allow-Origin: http://kbiao.me
Access-Control-Max-Age: 3628800
Access-Control-Allow-methods: GET, PUT, DELETE, POST
Access-Control-Allow-Header: content-type
Access-Control-Allow-Credentail: true

“Access-Control-Allow-Origin"表明它允许” http://kbiao.me "发起跨域请求

"Access-Control-Max-Age"表明在3628800秒内,不需要再发送预检验请求,可以缓存该结果(上面的资料上我们知道CROS协议中,一个AJAX请求被分成了第一步的OPTION预检测请求和正式请求)

"Access-Control-Allow-Methods"表明它允许GET、PUT、DELETE的外域请求

"Access-Control-Allow-Headers"表明它允许跨域请求包含content-type头

"Access-Control-Allow-Credentials"表明它允许cookies

  • 8
    点赞
  • 41
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值