解决SpringBoot项目有关跨域的问题,内含其他博客中不生效的解决方法

(前言:此方法可以快速解决有关请求跨域时的问题,重点在最后,可直接跳过去看)

场景:在使用amis框架搭建好前端后,出现了前端发送post请求,后端无法接收的问题;

而在反复检查路径无误后,通过F12看到问题出在了跨域这里
错误信息为:

Response to preflight request doesn t pass access control check: 
No  Access-Control-Allow-Origin  header is present on the requested resource.

还有

Response to preflight request doesn't pass access control check: 
The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'.
.....has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome-extension, edge, https, chrome-untrusted

之类
(这些错误我当时没有一一记录,事后只复盘了这几个…)

(这里报错是报405 METHOD NOT ALLOWED,但请求本身没问题,也提醒到碰到类似问题的朋友可以检查下是否也是因跨域请求而导致错误!)
起先,我是根据网上找的配置Cors的方案,进行的配置(这里引一个博客
https://blog.csdn.net/qq_31960623/article/details/118254754?ops_request_misc=&request_id=&biz_id=102&utm_term=springboot%E8%B7%A8%E5%9F%9F%E8%A7%A3%E5%86%B3%E6%96%B9%E6%A1%88&utm_medium=distribute.pc_search_result.none-task-blog-2allsobaiduweb~default-1-118254754.142v10control,157v5new_style2&spm=1018.2226.3001.4187)
我是copy这个的,但是无法解决(非恶意,侵删,顺便感谢这位博主),

一开始用了第一种也就是配置CorsConfig的方法:

@Configuration
public class GlobalCorsConfig {

    @Bean
    public CorsFilter corsFilter() {
        //1. 添加 CORS配置信息
        CorsConfiguration config = new CorsConfiguration();
        //放行哪些原始域
        config.addAllowedOrigin("*");
        //是否发送 Cookie
        config.setAllowCredentials(true);
        //放行哪些请求方式
        config.addAllowedMethod("*");
        //放行哪些原始请求头部信息
        config.addAllowedHeader("*");
        //暴露哪些头部信息
        config.addExposedHeader("*");
        //2. 添加映射路径
        UrlBasedCorsConfigurationSource corsConfigurationSource = new UrlBasedCorsConfigurationSource();
        corsConfigurationSource.registerCorsConfiguration("/**",config);
        //3. 返回新的CorsFilter
        return new CorsFilter(corsConfigurationSource);
    }
}
————————————————
版权声明:本文为CSDN博主「wh柒八九」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_31960623/article/details/118254754

是会报错的,包括使用第三种方法,即在类上加注解解决,如果按博主这样写:

@CrossOrigin(origins = "*")

会在项目启动时报如下错误:

org.springframework.beans.factory.BeanCreationException: 
Error creating bean with name 'requestMappingHandlerMapping' defined in class path resource 
[org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration$EnableWebMvcConfiguration.class]: 
Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: 
When allowCredentials is true, allowedOrigins cannot contain the special value "*" since thatcannot be set on the "Access-Control-Allow-Origin" response header. 
To allow credentials to a set of origins, list them explicitly or consider using "allowedOriginPatterns" instead.

以及

Caused by: java.lang.IllegalArgumentException: 
When allowCredentials is true, allowedOrigins cannot contain the special value "*" since that cannot be set on the "Access-Control-Allow-Origin" response header. 
To allow credentials to a set of origins, list them explicitly or consider using "allowedOriginPatterns" instead.

**

重点来了:

**
而根据阅读错误提示,如果将注解改为如下:

//在类上添加
@CrossOrigin(originPatterns = "*")

然后

//在方法上添加
@CrossOrigin(allowCredentials = "true")

就可以正常运行了!
如果要写配置类,应该这样写:

package com.example.back.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 corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedOriginPattern("*"); //主要就是这里的方法有变
        corsConfiguration.addAllowedHeader("*"); 
        corsConfiguration.addAllowedMethod("*"); 
        corsConfiguration.setAllowCredentials(true);
        return corsConfiguration;
    }

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", buildConfig()); // 对接口配置跨域设置
        return new CorsFilter(source);
    }
}

这次的教训就是,大家在平时开发时,碰到错误一定要认真看错误提醒,切莫盲目search解决方案!
(原因的话有空后补,其实从错误提示中,也已经解释的很明白了,简单说就是有的配置不能使用通配符*)

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值