解决Vue前端跨域问题

1、在项目目录下面建立config 配置包 

2、在配置包下建立CorsConfig类

3、该类里面的代码参考下面

package com.example.projectyuan.config;


import org.springframework.web.filter.CorsFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

@Configuration
public class CorsConfig {
    //当前跨域请求最大有效时长。这里默认1天
    private static final long MAX_AGE = 3600L * 24;

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        //允许跨域请求的域名,可以用*表示允许任何域名使用
        corsConfiguration.addAllowedOrigin("*");
        //允许任何头
        corsConfiguration.addAllowedHeader("*");
        //允许任何方法(post、get等)
        corsConfiguration.addAllowedMethod("*");
        //预检请求的有效期,单位为秒。有效期内,不会重复发送预检请求
        corsConfiguration.setMaxAge(MAX_AGE);
        source.registerCorsConfiguration("/**", corsConfiguration);
        return new CorsFilter(source);
    }
}

4、保存,然后重新启动项目

posted @ 2023-11-12 02:43  苏汐sama  阅读(83)  评论(0)    收藏  举报