前后端分离跨域springBoot跨域有效快速解决方案

之前一直听过跨域这个词,以前的项目也有跨域需要处理,但是自己未参与也未曾看过别人是怎么解决的。

最近有个前后端完全分离项目, 需要解决一下跨域问题;解决完了就简单在此记录一下;

同源策略:

请求的url地址,必须与浏览器上的url地址处于同域上,也就是域名,端口,协议相同.

比如:我在前端页面上的域名是3000端口,请求后台项目端口为8000的域名

这个时候在浏览器上会报错:

这样后台肯定是进不去,所以直接上代码。以下是spring boot 解决方案,

import org.springframework.boot.web.servlet.FilterRegistrationBean;
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 MyConfiguration {
    @Bean
    public FilterRegistrationBean corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        // 设置域名你要允许的网站,如果全允许则设为 *
        //config.addAllowedOrigin("http://127.0.0.1:3000");
       config.addAllowedOrigin("*");
        // 如果要限制 HEADER 或 METHOD 请自行更改
        config.addAllowedHeader("x-requested-with,content-type,requesttype");
        config.addAllowedMethod("*");
        source.registerCorsConfiguration("/**", config);
        FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
        // 这个顺序很重要哦,为避免麻烦请设置在最前
        bean.setOrder(0);
        return bean;
    }
}

页面ajax正常请求就可以访问了,url示例:

http://127.0.0.1:80/person/checkStatusPerson

如果有问题请及时留言,我会第一时间反馈,也可添加我的qq:983469079

猜你喜欢

转载自blog.csdn.net/Xiaodongge521/article/details/87921522
今日推荐