springboot配置允许跨域访问
因springboot框架通常用于前后端分离项目,因此需配置后台允许跨域访问(具体看注释),
配置类如下,将该类加入工程中即可。
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 suntongxin
* create on 2017年7月6日下午8:05:19
* all right reserved
*/
@configuration
public class corsconfig {
private corsconfiguration buildconfig() {
corsconfiguration corsconfiguration = new corsconfiguration();
corsconfiguration.addallowedorigin("*"); //允许任何域名
corsconfiguration.addallowedheader("*"); //允许任何头
corsconfiguration.addallowedmethod("*"); //允许任何方法
return corsconfiguration;
}
@bean
public corsfilter corsfilter() {
urlbasedcorsconfigurationsource source = new urlbasedcorsconfigurationsource();
source.registercorsconfiguration("/**", buildconfig()); //注册
return new corsfilter(source);
}
}前后端分离跨域问题的解决
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 static final long max_age = 24 * 60 * 60;
private corsconfiguration buildconfig() {
corsconfiguration corsconfiguration = new corsconfiguration();
corsconfiguration.addallowedorigin("*"); // 设置访问源地址
corsconfiguration.addallowedheader("*"); // 设置访问源请求头
corsconfiguration.addallowedmethod("*"); // 设置访问源请求方法
corsconfiguration.setmaxage(max_age);
return corsconfiguration;
}
@bean
public corsfilter corsfilter() {
urlbasedcorsconfigurationsource source = new urlbasedcorsconfigurationsource();
source.registercorsconfiguration("/**", buildconfig()); // 对接口配置跨域设置
return new corsfilter(source);
}
}
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论