Spring前后端跨域请求设置代码实例

2025-05-29 0 36

前后端项目分离,跨域请求时,后端的两种配置方式:

1.配置类:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34
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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持快网idc。

原文链接:https://www.cnblogs.com/helq/p/13336870.html

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 Spring前后端跨域请求设置代码实例 https://www.kuaiidc.com/119520.html

相关文章

发表评论
暂无评论