跨域请求
何谓跨域请求?简单来说,是浏览器的一种自我保护机制。Web请求连接中,有三大要素:地址ip、端口port、协议http/https,只要其中有一个不一致,浏览器将视其为跨域请求。
跨域请求
跨域请求不是一个新鲜的概念,或者说是一个落后的概念,网络安全的维护,已经不再是简单地进行跨域请求的限制,作为互联网研发的一员,我们时常觉得浏览器应该废弃跨区请求的限制。如何解除跨域请求的限制呢?
允许跨域配置
Java是目前后端最热门的开发语言,而SpringBoot作为后端接口开发目前最热门的框架,跨域运行的设置,十分简单。
SpringBoot代码编写
方案一
重新配置 CorsFilter
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; | |
/** | |
* 实现基本的跨域请求 | |
* @author IT小村 | |
* | |
*/ | |
public class CorsConfig { | |
private CorsConfiguration buildConfig() { | |
CorsConfiguration corsConfiguration = new CorsConfiguration(); | |
corsConfiguration.addAllowedOrigin("*"); // 允许任何域名使用 | |
corsConfiguration.addAllowedHeader("*"); // 允许任何头 | |
corsConfiguration.addAllowedMethod("*"); // 允许任何方法(post、get等)return corsConfiguration; | |
} | |
corsFilter() { | CorsFilter|
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); | |
source.registerCorsConfiguration("/**", buildConfig()); // 对接口配置跨域设置return new CorsFilter(source); | |
} | |
} |
方案二
实现 WebMvcConfigurer 接口,重写 addCorsMappings 方法。
import org.springframework.context.annotation.Configuration; | |
import org.springframework.web.servlet.config.annotation.CorsRegistry; | |
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; | |
/** | |
* 实现基本的跨域请求 | |
* @author IT小村 | |
* | |
*/ | |
public class WebAppConfigurer implements WebMvcConfigurer { | |
void addCorsMappings(CorsRegistry registry) { | |
registry.addMapping("/**") | |
.allowedOrigins("*") | |
.allowCredentials(true) | |
.allowedMethods("GET", "HEAD", "POST", "PUT", "DELETE","OPTIONS") | |
.maxAge(3600); | |
} | |
} |
其他
开发中跨域问题的频繁出现,主要原因在于互联网的高速发展,互联网产品更新迭代频繁,研发们不得推出高内聚低耦合的前后端分离开发模式,以便更加灵活地应对众多的技改需求。