springboot 跨域问题(CORS)
2021-04-19 18:28
标签:网站 actor family name new DDM ram tor ESS 跨域(CORS)是指不同域名之间相互访问。跨域,指的是浏览器不能执行其他网站的脚本,它是由浏览器的同源策略所造成的,是浏览器对于JavaScript所定义的安全限制策略。 也就是如果在A网站中,我们希望使用Ajax来获得B网站中的特定内容,如果A网站与B网站不在同一个域中,那么就出现了跨域访问问题。 同域: 1.@CrossOrigin注解 2.WebMvcConfigurer @Configuration .allowedOrigins("*") .allowCredentials(true) } 3.使用Filter方式进行设置使用Filter过滤器来过滤服务请求,向请求端设置Response Header(响应头部)的Access-Control-Allow-Origin属性声明允许跨域访问。 4.继承使用Spring Web中的CorsFilter springboot 跨域问题(CORS) 标签:网站 actor family name new DDM ram tor ESS 原文地址:https://www.cnblogs.com/michaelcnblogs/p/13287802.html 什么是跨域(CORS)
以上三个条件中有一个条件不同就会产生 跨域问题。
public class CorsConfiguration {
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE")
.allowedOrigins("*");
}
};
}@WebFilter
public class CorsFilter implements Filter {
// 日志对象
private static Logger logger = LoggerFactory.getLogger(CorsFilter.class);
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
chain.doFilter(req, res);
}
public void init(FilterConfig filterConfig) {
// something init
}
public void destroy() {
// destroy something
}
}
import org.springframework.stereotype.Component;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import java.util.Arrays;
/**
* 跨域访问配置
*
* @author Garyond
*/
@Component
public class CustomCorsFilter extends CorsFilter {
public CustomCorsFilter() {
super(configurationSource());
}
private static UrlBasedCorsConfigurationSource configurationSource() {
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
config.setMaxAge(36000L);
config.setAllowedMethods(Arrays.asList("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS"));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/v1/**", config);
return source;
}
}
上一篇:SpringMVC源码解析
下一篇:20-揭秘Python协程
文章标题:springboot 跨域问题(CORS)
文章链接:http://soscw.com/index.php/essay/76777.html