美文网首页
SpringBoot跨域的配置

SpringBoot跨域的配置

作者: dwwl | 来源:发表于2019-07-23 11:45 被阅读0次
package com.teda.z4.webApp;

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;

/**
 * Springboot方式设置跨域,比Filter更方便
 * 
 */
@Configuration
public class CorsConfig
{

    private CorsConfiguration buildConfig()
    {

        CorsConfiguration corsConfiguration = new CorsConfiguration();
        //服务器允使的请求域名
        corsConfiguration.addAllowedOrigin("*"); 
        //服务器支持的所有头信息字段,不限于浏览器在"预检"中请求的字段
        corsConfiguration.addAllowedHeader("*"); 
        //服务器支持的所有跨域请求的方法
        corsConfiguration.addAllowedMethod("*"); 
        //本次预检请求的有效期,单位为秒,有效期内不用发出另一条预检请求
        corsConfiguration.setMaxAge(new Long(7200));

        corsConfiguration.setAllowCredentials(true);//设置跨域问题
        return corsConfiguration;
    }

    @Bean
    public CorsFilter corsFilter()
    {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", buildConfig());
        return new CorsFilter(source);
    }
}

相关文章

网友评论

      本文标题:SpringBoot跨域的配置

      本文链接:https://www.haomeiwen.com/subject/eddolctx.html