当前位置: 代码网 > it编程>编程语言>Java > springboot如何配置允许跨域访问

springboot如何配置允许跨域访问

2024年08月09日 Java 我要评论
springboot配置允许跨域访问因springboot框架通常用于前后端分离项目,因此需配置后台允许跨域访问(具体看注释),配置类如下,将该类加入工程中即可。import org.springfr

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);
    }
}

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com