Spring前后端跨域請求設(shè)置代碼實(shí)例
前后端項(xiàng)目分離,跨域請求時(shí),后端的兩種配置方式:
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();
//設(shè)置屬性
//允許跨域請求的地址,*表示所有
configuration.addAllowedOrigin("*");
//配置跨域的請求頭
configuration.addAllowedHeader("*");
//配置跨域的請求方法
configuration.addAllowedMethod("*");
//表示跨域請求的時(shí)候使用的是否是同一個(gè)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
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
SSM項(xiàng)目使用攔截器實(shí)現(xiàn)登錄驗(yàn)證功能
這篇文章主要介紹了在SSM項(xiàng)目中如何使用攔截器,實(shí)現(xiàn)登錄驗(yàn)證功能。文中的實(shí)現(xiàn)步驟講解詳細(xì),感興趣的小伙伴可以了解一下2022-01-01
Mybatis攔截器如何實(shí)現(xiàn)數(shù)據(jù)權(quán)限過濾
本文介紹了MyBatis攔截器的使用,通過實(shí)現(xiàn)Interceptor接口對SQL進(jìn)行處理,實(shí)現(xiàn)數(shù)據(jù)權(quán)限過濾功能,通過在本地線程變量中存儲(chǔ)數(shù)據(jù)權(quán)限相關(guān)信息,并在攔截器的intercept方法中進(jìn)行SQL增強(qiáng)處理2024-12-12
SpringBoot 整合 Avro 與 Kafka的詳細(xì)過程
本文介紹了如何在Spring Boot中使用Avro和Kafka進(jìn)行數(shù)據(jù)的序列化和反序列化,并通過MyBatisPlus將數(shù)據(jù)存入數(shù)據(jù)庫,感興趣的朋友跟隨小編一起看看吧2024-12-12
詳解Java編程中統(tǒng)一資源定位符URL的相關(guān)使用
這篇文章主要介紹了Java編程中統(tǒng)一資源定位符URL的相關(guān)使用,是Java網(wǎng)絡(luò)編程中的基礎(chǔ)知識(shí),需要的朋友可以參考下2015-10-10
SpringBoot做junit測試的時(shí)候獲取不到bean的解決
這篇文章主要介紹了SpringBoot做junit測試的時(shí)候獲取不到bean的解決方案,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-09-09
springSecurity自定義登錄接口和JWT認(rèn)證過濾器的流程
這篇文章主要介紹了springSecurity自定義登陸接口和JWT認(rèn)證過濾器的相關(guān)資料,本文給大家介紹的非常詳細(xì),感興趣的朋友跟隨小編一起看看吧2024-12-12
SpringBoot Mybatis Plus公共字段自動(dòng)填充功能
這篇文章主要介紹了SpringBoot Mybatis Plus公共字段自動(dòng)填充功能的相關(guān)資料,需要的朋友可以參考下2017-04-04

