SpringBoot配置Cors解决跨域请求问题

2023-01-08 19:36:22

解决方法

编写配置类CorsConfig.class

package com.vueserver.config;

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: fanli
 * @Date: 2018/8/3 12:40
 * @Description: 前后端联调-跨域配置
 */
@Configuration
public class CorsConfig {

    private CorsConfiguration buildConfig() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedOrigin("*"); // 源地址
        corsConfiguration.addAllowedHeader("*"); // 请求头
        //corsConfiguration.addAllowedMethod("*"); // 请求方法,restful带着
        return corsConfiguration;
    }

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", buildConfig()); // 所有的api都是可跨域的
        return new CorsFilter(source);
    }

}
  • 作者:java冯坚持
  • 原文链接:https://blog.csdn.net/qq_40036754/article/details/89073504
    更新时间:2023-01-08 19:36:22