Spring-boot中完美实现Post|Spring-boot中完美实现Post,Get方式的跨域请求
由于在javascript页面中请求数据涉及到跨域请求,困扰很久才处理完成,所以记录下来这次操作经验 1.在spring-boot中设置过滤器 ,直接上代码
@Component
public class CorsFilter implements Filter {final static org.slf4j.Logger logger = org.slf4j.LoggerFactory
.getLogger(CorsFilter.class);
public CorsFilter(UrlBasedCorsConfigurationSource source) {}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, PUT");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with,Origin,Content-Type, Accept");
chain.doFilter(req, res);
}public void init(FilterConfig filterConfig) {
}public void destroy() {
}
}
2.在Application中配置全局过滤器
/**
* 跨域配置
* @return
*/
private CorsConfiguration buildConfig() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOrigin("*");
corsConfiguration.addAllowedHeader("*");
corsConfiguration.addAllowedMethod("*");
return corsConfiguration;
}/**
* 跨域过滤器
* @return
*/
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", buildConfig());
return new CorsFilter(source);
}
【Spring-boot中完美实现Post|Spring-boot中完美实现Post,Get方式的跨域请求】至此完美解决Post的对象请求还有正常的GET方式请求数据,经实践可正常使用
推荐阅读
- 热闹中的孤独
- Shell-Bash变量与运算符
- JS中的各种宽高度定义及其应用
- 2021-02-17|2021-02-17 小儿按摩膻中穴-舒缓咳嗽
- 深入理解Go之generate
- 异地恋中,逐渐适应一个人到底意味着什么()
- 我眼中的佛系经纪人
- 《魔法科高中的劣等生》第26卷(Invasion篇)发售
- “成长”读书社群招募
- 2020-04-07vue中Axios的封装和API接口的管理