spring跨域,前端使用FormData()完成跨域提交表单

1、spring boot完成跨域上传表单

后台代码

前端代码

2、spring MVC完成跨域上传表单

后台代码

前端代码跟springboot是一样的。

代码过几天我都放到了GitHub上,需要的可以克隆下来

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot中配置跨域,可以通过在SecurityConfig中配置CorsFilter来实现。 首先,在pom.xml文件中添加以下依赖: ```xml <!-- Spring Boot Security --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <!-- Spring Boot Web --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> ``` 然后,在SecurityConfig中添加以下配置: ```java @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable() .authorizeRequests().anyRequest().authenticated() .and().cors().and().httpBasic(); } @Bean public CorsConfigurationSource corsConfigurationSource() { CorsConfiguration configuration = new CorsConfiguration(); configuration.setAllowedOrigins(Arrays.asList("http://localhost:8080")); configuration.setAllowedMethods(Arrays.asList("GET","POST")); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", configuration); return source; } } ``` 上述代码中,我们首先禁用了CSRF保护,然后配置了任何请求都需要进行身份验证,接着通过cors()方法启用跨域,最后使用httpBasic()方法启用HTTP基本身份验证。 同时,我们还定义了一个corsConfigurationSource()方法,该方法返回一个CorsConfigurationSource对象,其中我们指定了允许的来源和方法。 需要注意的是,在allowedOrigins()方法中需要指定前端服务器的地址。如果允许所有来源,可以将allowedOrigins()方法调用替换为allowCredentials(true).allowedOriginPatterns("*")。 最后,需要在前端页面中发送请求时设置withCredentials属性为true,以便将Cookies发送到服务器。 ```javascript axios.defaults.withCredentials = true; axios.get('http://localhost:8088/api/user').then(response => { console.log(response.data); }); ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值