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
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
Mybatis攔截器如何實現(xiàn)數(shù)據(jù)權限過濾
本文介紹了MyBatis攔截器的使用,通過實現(xiàn)Interceptor接口對SQL進行處理,實現(xiàn)數(shù)據(jù)權限過濾功能,通過在本地線程變量中存儲數(shù)據(jù)權限相關信息,并在攔截器的intercept方法中進行SQL增強處理2024-12-12
SpringBoot 整合 Avro 與 Kafka的詳細過程
本文介紹了如何在Spring Boot中使用Avro和Kafka進行數(shù)據(jù)的序列化和反序列化,并通過MyBatisPlus將數(shù)據(jù)存入數(shù)據(jù)庫,感興趣的朋友跟隨小編一起看看吧2024-12-12
詳解Java編程中統(tǒng)一資源定位符URL的相關使用
這篇文章主要介紹了Java編程中統(tǒng)一資源定位符URL的相關使用,是Java網(wǎng)絡編程中的基礎知識,需要的朋友可以參考下2015-10-10
SpringBoot做junit測試的時候獲取不到bean的解決
這篇文章主要介紹了SpringBoot做junit測試的時候獲取不到bean的解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-09-09
springSecurity自定義登錄接口和JWT認證過濾器的流程
這篇文章主要介紹了springSecurity自定義登陸接口和JWT認證過濾器的相關資料,本文給大家介紹的非常詳細,感興趣的朋友跟隨小編一起看看吧2024-12-12
SpringBoot Mybatis Plus公共字段自動填充功能
這篇文章主要介紹了SpringBoot Mybatis Plus公共字段自動填充功能的相關資料,需要的朋友可以參考下2017-04-04

