Spring前后端跨域請求設置


前后端項目分離,跨域請求時,后端的兩種配置方式:

1.配置類:

package com.helq3.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;

/**
 * 跨域全局配置
 */
@Configuration
public class CorsConfig {
    private CorsConfiguration buildConfig(){

        CorsConfiguration configuration = new CorsConfiguration();
        //設置屬性
        //允許跨域請求的地址,*表示所有
        configuration.addAllowedOrigin("*");
        //配置跨域的請求頭
        configuration.addAllowedHeader("*");
        //配置跨域的請求方法
        configuration.addAllowedMethod("*");
        //表示跨域請求的時候使用的是否是同一個session
        configuration.setAllowCredentials(true);
        return configuration;
    }
    @Bean
    public CorsFilter corsFilter(){
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**",buildConfig());
        return new CorsFilter(source);
    }
}

2.Controller上面配置

@CrossOrigin(origins = "*",allowedHeaders = "*",methods = {},allowCredentials = "true")
public class TestController {
}

 3.Ant Design Vue 中,在src/util/request.js中增加

axios.defaults.withCredentials = true


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM