CORS是一个W3C标准,全称是"跨域资源共享"(Cross-origin resource sharing)。它允许浏览器向跨源服务器,发出XMLHttpRequest请求,从而克服了AJAX只能同源使用的限制。只要服务器实现了CORS接口,就可以跨源通信。
CORS有两种请求,简单请求和非简单请求。
跨域就等于从百度访问谷歌的资源,URL由协议、域名、端口和路径组成,如果两个URL的协议、域名和端口相同,则表示他们同源。相反,只要协议
,域名
,端口
有任何一个的不同,就被当作是跨域。
浏览器采用同源策略,禁止页面加载或执行与自身来源不同的域的任何脚本。
假设在服务器8080和8088这2个端口同时挂载不同代码
@RequestMapping ("/")
@ResponseBody
public String index(HttpServletResponse response) {
return "跨域内容显示";
}
@RequestMapping("/cors")
public String cors(HttpServletResponse response) {
return "/cors";
}
cors.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.
被调用方需要的解决方案:
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
allowedAccessFilter
aaa.bbb.ccc.ddd.CorsFilter
allowedAccessFilter
/registeryuyue/*
@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,而下面全局配置的方式可以应用于整个工程
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);
}
}
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