1.10 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;
/**
 * @Description:
 *   设置后台允许跨域请求
 */
@Configuration
public class CorsConfig {
    public CorsConfig() {  }

    @Bean
    public CorsFilter corsFilter() {
        // 1. 添加cors配置信息
        CorsConfiguration config = new CorsConfiguration();
        //设置访问源地址
        config.addAllowedOrigin("http://localhost:8080");
        //config.addAllowedOrigin("http://shop.z.mukewang.com:8080");
        //config.addAllowedOrigin("http://center.z.mukewang.com:8080");
        //config.addAllowedOrigin("http://shop.z.mukewang.com");
        //config.addAllowedOrigin("http://center.z.mukewang.com");
        //config.addAllowedOrigin("*");
        // 设置是否发送cookie信息
        config.setAllowCredentials(true);
        // 设置允许请求的方式
        config.addAllowedMethod("*");
        // 设置允许的header
        config.addAllowedHeader("*");

        // 2. 为url添加映射路径
        UrlBasedCorsConfigurationSource corsSource = new UrlBasedCorsConfigurationSource();
        corsSource.registerCorsConfiguration("/**", config);
        // 3. 返回重新定义好的corsSource
        return new CorsFilter(corsSource);
    }

}

你可能感兴趣的:(java架构笔记,spring,boot,后端,java)